How Python reads, writes, and manages files on your system
Many programs need to store or retrieve data from files. Python makes file handling simple and powerful with built‑in functions.
Use the open() function to work with files:
file = open("example.txt", "r") # r = read mode
"r" — read (file must exist)"w" — write (creates or overwrites)"a" — append (adds to the end)"r+" — read and writeRead the entire file:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Read line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Read into a list:
with open("example.txt", "r") as file:
lines = file.readlines()
Write text to a file (overwrites existing content):
with open("output.txt", "w") as file:
file.write("Hello, file!")
Add new content without deleting existing data:
with open("output.txt", "a") as file:
file.write("\nAnother line.")
The with keyword automatically closes the file when done. This is the recommended way to handle files.
Use the os module to work with file paths:
import os
print(os.getcwd()) # current directory
print(os.path.exists("data.txt"))
File operations often require error handling:
try:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found!")
Now that you can read and write files, you're ready to learn how Python handles errors more broadly in Lesson 11: Error Handling with try/except.
← Back to Lesson Index