Python File Handling Introduction
In this page:
Introduction to File Streams
File handling is how a program reads data from, or writes data to, files that persist on disk after the program ends -- unlike variables in memory, a saved file's contents survive between separate runs of your script.
Example: Introduction to File Streams
with open("notes.txt", "w") as f:
f.write("saved to disk")
with open("notes.txt", "r") as f:
print(f.read())
The open() Function
open() is the entry point for all file work -- it takes a file path and a mode string (r for reading, w for writing, and others) and returns a file object you then call methods like .read() or .write() on.
Example: The open() Function
f = open("notes.txt", "w")
f.write("hello")
f.close()
f = open("notes.txt", "r")
print(f.read())
f.close()
Closing Files
Every file you open should eventually be closed with .close() -- this releases the operating system's file handle and, for files opened in write mode, ensures buffered data actually gets flushed to disk rather than lost if the program exits unexpectedly.
Example: Closing Files
f = open("notes.txt", "w")
f.write("data")
f.close()
print(f.closed)
The with Statement
The 'with open(...) as f:' pattern automatically calls .close() for you once the indented block ends, even if an exception is raised inside it -- this makes it the recommended way to work with files instead of manually pairing open() and close() calls.
Example: The with Statement
with open("notes.txt", "w") as f:
f.write("safe write")
print(f.closed) # automatically closed after the block
File Modes Overview
Beyond basic r (read) and w (write, which erases existing content), a appends new data to a file's end without touching what's already there, and x creates a brand-new file but raises FileExistsError if one already exists at that path -- useful as a safety check against accidental overwrites.
Example: File Modes Overview
with open("log.txt", "w") as f:
f.write("first line\n")
with open("log.txt", "a") as f:
f.write("appended line\n")
with open("log.txt", "r") as f:
print(f.read())
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: