Python reads and writes files with a single function, open() — one entry point for both reading and writing.
The idiomatic way to work with a file in Python is the with statement, which automatically closes the file when the block ends — even if an error happens partway through, so you never have to remember to close it manually:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
# the file is automatically closed here, guaranteedAlways prefer with over manual close()
with is a context manager — a general Python pattern for "set something up, guarantee it gets cleaned up afterward," used for far more than just files (database connections and network sockets follow the same pattern). Prefer it over manually calling .close() yourself.
with open("notes.txt", "w") as file:
file.write("Hello, file!") # "w" overwrites
with open("notes.txt", "a") as file:
file.write("\nAnother line.") # "a" appends insteadFor a large file, looping over the file object directly reads one line at a time instead of loading everything into memory at once:
with open("notes.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes the trailing newline| Mode | Meaning |
|---|---|
| "r" | Read (default) — the file must already exist |
| "w" | Write — creates the file if missing, overwrites if it exists |
| "a" | Append — creates the file if missing, adds to the end if it exists |
Opening a missing file with "r" raises a FileNotFoundError — checking first with the standard library's pathlib avoids that, and is the modern, recommended way to work with file paths in Python:
from pathlib import Path
file = Path("notes.txt")
if file.exists():
print(file.read_text())
else:
print("File not found.")pathlib can fully replace open() for reading and writing too (file.read_text(), file.write_text(...)) — worth knowing it exists, even though this lesson sticks with open() since it's the more universally recognized starting point.
Never trust a user-supplied file path
Any file path used with these functions should never come directly from user input without careful validation — a user-controlled path is a real security risk. This matters even more once file uploads are involved.