File handling in Python allows you to read from and write to files, making it possible to store, retrieve, and process data. Python provides built-in functions and modes for file operations:
r– Read (default)w– Write (overwrite)a– Appendr+– Read and write
File operations are typically used with the with statement for automatic resource management.
Why File Handling Is Important
- Store and retrieve data for persistent storage
- Process logs, configurations, and datasets
- Enable real-world applications like report generation, data pipelines, and automation
- Prevent data loss with proper file operations
Example 1: Reading a File
with open("example.txt", "r") as file:
content = file.read()
print(content)
- Safely reads the file
- Automatically closes the file after the block
Example 2: Writing to a File
with open("example.txt", "w") as file:
file.write("Hello Python!\n")
file.write("File handling is easy.")
- Overwrites the file if it exists
- Creates the file if it doesn’t exist
Example 3: Appending to a File
with open("example.txt", "a") as file:
file.write("\nAdding a new line.")
- Adds content to the end of the file without overwriting
Example 4: Real-World Scenario – Logging Events
def log_event(event):
with open("app.log", "a") as log_file:
log_file.write(f"{event}\n")
log_event("User logged in")
log_event("User updated profile")
- Useful for maintaining application logs
- Ensures all events are recorded sequentially
Example 5: Reading File Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
- Efficient for large files
- Processes one line at a time to save memory
Best Practices
✔ Always use with to manage files and avoid leaks
✔ Handle exceptions using try-except for file operations
✔ Use r+ or a mode carefully to prevent accidental data loss
✔ Close files manually if not using with
Conclusion
Python file handling techniques allow you to read, write, and manage data efficiently. Mastering these operations is essential for real-world applications like logging, data storage, automation, and report generation.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/