Python File Handling – Read, Write, Append & Manage Files Easily
Introduction – Why File Handling Matters in Python
Handling files is essential for storing data permanently. Python’s built-in file handling functions make it easy to create, read, update, or delete files—supporting everything from configuration files and logs to data pipelines.
What You Will Learn:
- Opening, reading, and writing files using
open() - File modes:
r,w,a,x,b,t, and+ - Functions like
read(),write(),readlines(),writelines() - Exception handling with
try...exceptfor file errors
1. Opening and Closing Files
Using open() Function
file = open("example.txt", "r")
print(file.read())
file.close()
Explanation:
"r"opens the file in read mode.close()frees system resources and ensures changes are saved.
Tip: Always close files manually or use a with block for auto-closure.
Using with Statement (Best Practice)
with open("example.txt", "r") as file:
content = file.read()
print(content)
This ensures the file is closed automatically after the block ends.
2. File Modes in Python
| Mode | Description |
|---|---|
'r' | Read mode (default). Errors if file doesn’t exist |
'w' | Write mode. Overwrites or creates new file |
'a' | Append mode. Adds to existing file or creates new |
'x' | Create mode. Fails if file exists |
'b' | Binary mode (e.g., images) |
't' | Text mode (default) |
'+' | Read and write combined (e.g., r+, w+) |
3. Reading from Files
read()
with open("example.txt", "r") as f:
print(f.read())
Reads entire file content as a string.
readline()
with open("example.txt", "r") as f:
print(f.readline())
Reads one line at a time.
readlines()
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
Returns a list of lines in the file.
4. Writing to Files
write()
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
Writes a string to file. Must add \n for line breaks.
writelines()
lines = ["Line 1\n", "Line 2\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
Writes multiple strings (as list) into file.
5. Appending to Files
with open("output.txt", "a") as f:
f.write("New Line\n")
Adds content at the end without overwriting existing data.
6. Handling File Not Found Errors
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File does not exist.")
Prevents crash if file is missing by using try...except.
Best Practices
- Use
with open()for safety and simplicity. - Choose correct file mode (
'r','w','a') as per operation. - Use
os.path.exists()to check file presence (optional). - Handle exceptions gracefully.
Summary – Recap & Next Steps
Python file handling is crucial for working with persistent data sources. From reading logs to writing reports, it simplifies data access and manipulation.
Key Takeaways:
- Use
open()with correct modes (r,w,a,x) - Use
read(),write(),readlines()for I/O - Always use
with open()to manage files efficiently - Handle file-related errors with
try...except
Real-World Relevance:
This is widely used in data logging, report generation, configuration management, and automation.
FAQ – Python File Handling
How do I safely open and close a file in Python?
Use:
with open("file.txt", "r") as f:
print(f.read())
This auto-closes the file.
What’s the difference between w and a?
'w' overwrites the file; 'a' appends data at the end.
How do I read a file line by line?
Use readline() or a loop:
with open("file.txt", "r") as f:
for line in f:
print(line)How to handle missing file errors?
Use try...except FileNotFoundError block.
What’s the difference between text and binary mode?
't' is for human-readable text. 'b' is for non-text files like images or audio.
Share Now :
