Sooner or later almost every real program needs to read something from disk or save something to it — a config file, a log, a CSV export, whatever it might be. Python makes this refreshingly painless compared to a lot of languages.
Writing to a file
with open("notes.txt", "w") as f:
f.write("Hello, file!")The with block is the important part here, and it's worth pausing on. It guarantees the file gets closed properly once you're done with it, even if something goes wrong halfway through writing. Without it, you would have to remember to call f.close() yourself, and forgetting to close a file is a classic, sneaky source of bugs, especially on Windows where a still-open file can refuse to be deleted or renamed by another program.
Reading a file back
with open("notes.txt", "r") as f:
content = f.read()
print(content)Reading line by line
For a bigger file, reading the whole thing into memory at once isn't always ideal. Looping over the file directly reads it one line at a time instead:
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())That .strip() at the end removes the trailing newline character that comes along with each line — forget it, and you won'tice odd extra blank-looking gaps whenever you print the lines out.
The write modes, quickly
- "w" — write, and overwrite the file completely if it already exists. Be careful with this one.
- "a" — append, adding new content to the end without touching what is already there.
- "r" — read, the default if you leave the mode out entirely.
What happens if the file doesn't exist?
Opening a file in read mode when it doesn't exist raises a FileNotFoundError, which will crash your program unless you handle it. Wrapping the open call in a try/except block is the usual fix, something the next-but-one tutorial on error handling covers properly, but it's worth knowing this particular error exists before it surprises you the first time.
Working with paths sensibly
If your program deals with more than a file or two, the pathlib module is worth knowing about early rather than gluing file paths together as raw strings, especially since Windows and Mac or Linux use different slash characters in their paths, and pathlib quietly handles that difference for you.