Movatterモバイル変換


[0]ホーム

URL:


File I/O

Reading and writing files.

Working with paths

In [1]:
frompathlibimportPathcurrent_file=Path("file_io.ipynb").resolve()print(f"current file:{current_file}")# Note: in .py files you can get the path of current file by Path(__file__)current_dir=current_file.parentprint(f"current directory:{current_dir}")data_dir=current_dir.parent/"data"print(f"data directory:{data_dir}")
current file: /Users/jerrypussinen/github/jerry-git/learn-python3/notebooks/beginner/notebooks/file_io.ipynbcurrent directory: /Users/jerrypussinen/github/jerry-git/learn-python3/notebooks/beginner/notebooksdata directory: /Users/jerrypussinen/github/jerry-git/learn-python3/notebooks/beginner/data

Checking if path exists

In [2]:
print(f"exists:{data_dir.exists()}")print(f"is file:{data_dir.is_file()}")print(f"is directory:{data_dir.is_dir()}")
exists: Trueis file: Falseis directory: True

Reading files

In [3]:
file_path=data_dir/"simple_file.txt"withopen(file_path)assimple_file:forlineinsimple_file:print(line.strip())
First lineSecond lineThirdAnd so the story goes!

Thewith statement is for obtaining acontext manager that will be used as an execution context for the commands inside thewith. Context managers guarantee that certain operations are done when exiting the context.

In this case, the context manager guarantees thatsimple_file.close() is implicitly called when exiting the context. This is a way to make developers life easier: you don't have to remember to explicitly close the file you openened nor be worried about an exception occuring while the file is open. Unclosed file maybe a source of a resource leak. Thus, prefer usingwith open() structure always with file I/O.

To have an example, the same as above without thewith.

In [4]:
file_path=data_dir/"simple_file.txt"# THIS IS NOT THE PREFERRED WAYsimple_file=open(file_path)forlineinsimple_file:print(line.strip())simple_file.close()# This has to be called explicitly
First lineSecond lineThirdAnd so the story goes!

Writing files

In [5]:
new_file_path=data_dir/"new_file.txt"withopen(new_file_path,"w")asmy_file:my_file.write("This is my first file that I wrote with Python.")

Now go and check that there is a new_file.txt in the data directory. After that you can delete the file by:

In [6]:
ifnew_file_path.exists():# make sure it's therenew_file_path.unlink()

[8]ページ先頭

©2009-2025 Movatter.jp