Python File Handling – Read, Write, and Manage Files
Python provides built-in functions to create, read, write, and append files — allowing your programs to store and access data anytime.
Why File Handling?
- Store user data (like login info).
- Save results (logs, outputs, reports).
- Work with external data (CSV, JSON, etc.)
Opening a File
file = open("example.txt", "mode")
| Mode |
Meaning |
'r' |
Read (default) |
'w' |
Write (overwrite) |
'a' |
Append |
'x' |
Create new file |
'b' |
Binary mode (e.g., images) |
't' |
Text mode (default) |
Reading from a File
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Read Line-by-Line
for line in open("example.txt"):
print(line)
Writing to a File
file = open("example.txt", "w")
file.write("Hello, world!\n")
file.write("Python File Handling is easy.")
file.close()
Note: "w" mode will overwrite the file if it already exists.
Appending to a File
file = open("example.txt", "a")
file.write("\nThis line is added at the end.")
file.close()
Best Practice: Use with Statement (Auto Closes the File)
with open("example.txt", "r") as file:
data = file.read()
print(data)
Useful File Methods
file.read() # Read entire file
file.readline() # Read one line
file.readlines() # Read all lines (returns list)
file.write("text") # Write string to file
file.close() # Always close the file
Example: File Handling Workflow
filename = "notes.txt"
# Write
with open(filename, "w") as f:
f.write("Welcome to Python File Handling!\n")
# Append
with open(filename, "a") as f:
f.write("This line is added later.\n")
# Read
with open(filename, "r") as f:
print(f.read())
Error Handling (Optional)
try:
with open("file.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found.")
Summary
| Task |
Method |
| Open file |
open("file.txt", "r") |
| Read file |
read( ), readline( ), readlines( ) |
| Write file |
write( ) |
| Append to file |
Use mode "a" |
| Safe handling |
Use with statement |