Python reads and writes files with open() — the equivalent of PHP's fopen()/file_get_contents() family, unified into one function.
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, unlike PHP's manual fclose():
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 |
Never trust a user-supplied file path
Just like PHP, 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.