Onto file handling in Python. Opening files, reading and writing content, working with paths, and handling the errors that come up in real projects.
Opening a file
Use the built-in open() function. Pass the filename and an optional mode:
file = open('example.txt', 'r')
'r' is read mode. Other common modes: 'w' (write), 'a' (append), 'b' (binary).
Reading from a file
Once open in read mode, you have several options:
- Read the entire file:
read()returns everything as one string.
content = file.read()
print(content)
- Read line by line:
readline()returns one line at a time.
line = file.readline()
while line:
print(line, end='')
line = file.readline()
- Read all lines into a list:
readlines()returns a list of strings.
lines = file.readlines()
print(lines)
Writing to a file
Open in write ('w') or append ('a') mode:
- Write mode: creates or overwrites the file.
with open('example.txt', 'w') as file:
file.write("Hello Python!")
- Append mode: adds to the end without deleting existing content.
with open('example.txt', 'a') as file:
file.write("\nAppend this line.")
Using the with statement
with closes the file automatically when the block finishes, even if an exception is raised. Use it by default:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Binary files
For images, PDFs, and other non-text files, use 'rb' or 'wb':
with open('example.pdf', 'rb') as file:
content = file.read()
File paths
Paths differ between operating systems. os.path helps you build them portably:
import os
file_path = os.path.join('folder', 'example.txt')
with open(file_path, 'r') as file:
print(file.read())
Error handling
Files go missing. Wrap file operations in try-except:
try:
with open('non_existent_file.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print("The file does not exist")
JSON files
The json module reads and writes JSON data:
import json
# Writing JSON
data = {"name": "John", "age": 30, "city": "New York"}
with open('data.json', 'w') as file:
json.dump(data, file)
# Reading JSON
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
Use with for every file operation, handle exceptions, and pick the right mode for the job.

