File Handling in Python
To work with a file in Python, you open it, do something, and close it. The safest way uses a with block, which closes the file for you automatically:
# Write some text to a file
with open("notes.txt", "w") as file:
file.write("Hello from Python!\n")
file.write("This is line two.\n")
# Read it back
with open("notes.txt", "r") as file:
content = file.read()
print(content)
The with open(...) as file: pattern is the modern standard — let's understand why and how.
File modes
The second argument to open() is the mode — it tells Python what you intend to do:
"r"— read (the default). Errors if the file doesn't exist."w"— write. Creates the file, or erases it if it already exists."a"— append. Adds to the end without erasing existing content."x"— create. Errors if the file already exists.
# "w" overwrites — be careful!
with open("log.txt", "w") as f:
f.write("First entry\n")
# "a" adds to the end, keeping what's there
with open("log.txt", "a") as f:
f.write("Second entry\n")
Reading files
There are several ways to read, depending on what you need:
# Read the whole file as one string
with open("notes.txt", "r") as f:
text = f.read()
# Read all lines into a list
with open("notes.txt", "r") as f:
lines = f.readlines() # ['line1\n', 'line2\n', ...]
# Best for large files: loop line by line (memory-friendly)
with open("notes.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes the trailing newline
Looping over the file object directly is the recommended way for big files because it reads one line at a time instead of loading everything into memory.
Why use with?
If you open a file the old way with open() and forget to call .close(), the file may stay locked or data may not be saved properly. The with block guarantees the file is closed even if an error happens inside it:
# The 'with' block closes the file automatically — even on errors
with open("data.txt", "w") as f:
f.write("Safe and clean")
# file is now closed here, no manual close() needed
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesA practical example
# Save a list of tasks, then read them back
tasks = ["Buy books", "Finish project", "Call mentor"]
# Write each task on its own line
with open("todo.txt", "w") as f:
for task in tasks:
f.write(task + "\n")
# Read and number them
with open("todo.txt", "r") as f:
for number, line in enumerate(f, start=1):
print(f"{number}. {line.strip()}")
# 1. Buy books
# 2. Finish project
# 3. Call mentor
Working with file paths and encoding
When reading text, it's good practice to specify the encoding, especially for files with non-English characters:
# utf-8 handles most languages and symbols correctly
with open("notes.txt", "r", encoding="utf-8") as f:
print(f.read())
Common mistakes
- Using
"w"when you meant"a": Mode"w"wipes the file's contents the moment you open it. Use"a"to add without erasing. - Forgetting to close (without
with): If you use bareopen(), you must call.close(), or data may not be written. Just usewithto avoid the problem entirely. - Reading a file that doesn't exist: Mode
"r"raises aFileNotFoundError. Check the path, or wrap it in a try/except. - Forgetting newlines when writing:
f.write("line")doesn't add a line break. Add"\n"yourself if you want separate lines. - Leftover newlines when reading: Lines read from a file include a trailing
\n. Use.strip()to clean them.
FAQ
What's the difference between read() and readlines()?
read() returns the entire file as a single string. readlines() returns a list where each element is one line.
How do I check if a file exists before opening it?
Use os.path.exists("file.txt") from the os module, or Path("file.txt").exists() from pathlib.
Can I read and write at the same time?
Yes, with modes like "r+", but it's tricky for beginners. It's usually clearer to read, process in memory, then write separately.
File handling pairs well with Exception Handling in Python for dealing with missing files gracefully, and with Modules, Packages & pip for tools like pathlib. More topics on the Python learning hub.
Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesInstructor, Infoplanet
Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.
Related guides
Dictionaries in Python
Understand Python dictionaries — storing data as key-value pairs — including adding, accessing, updating, looping, and safely reading values with .get().
Exception Handling in Python
Handle errors gracefully in Python with try, except, else, and finally — so your program responds to problems instead of crashing.
Functions in Python
Define and use functions in Python — parameters, return values, default and keyword arguments — to write reusable, readable code.
