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") # writes and persists to disk
with open("notes.txt", "r") as f:
print(f.read()) # reads it back, even in a fresh run
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") # "w" mode opens the file for writing
f.write("hello")
f.close()
f = open("notes.txt", "r") # "r" mode opens the file for reading
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() # releases the file handle and flushes buffered data
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") # "w" mode starts the file fresh
with open("log.txt", "a") as f:
f.write("appended line\n") # "a" mode adds to the end without erasing
with open("log.txt", "r") as f:
print(f.read())
- Opening a file and never closing it, which can leave data unwritten or the file locked; use
with open(...). - Using the wrong mode, such as
"w"when you meant"r", which truncates the file and destroys its contents. - Giving a relative path that does not match the current working directory, which raises
FileNotFoundError.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: