File handling in Python allows you to read from and write to files. Python provides built-in functions to handle files efficiently, making it easy to store and retrieve data.
Why File Handling Is Important
File handling is useful to:
- Store data permanently
- Read and process external data
- Log information
- Work with large datasets
Example:
file = open("example.txt", "w")
file.write("Hello Python")
file.close()
Opening Files in Python
The open() function is used with two main arguments: file name and mode.
File Modes
| Mode | Description |
|---|---|
| r | Read (default) |
| w | Write (creates/overwrites) |
| a | Append |
| r+ | Read and write |
| x | Create a new file |
Reading Files
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line)
Writing to Files
with open("example.txt", "w") as file:
file.write("Python file handling example.")
Appending to Files
with open("example.txt", "a") as file:
file.write("\nAppending new line.")
Using with Statement
The with statement automatically closes the file after use.
with open("example.txt", "r") as file:
content = file.read()
Common File Handling Errors
❌ FileNotFoundError – file does not exist
❌ IOError – problem in reading/writing
❌ Forgetting to close the file
Best Practices
✔ Always use with statement
✔ Use proper file modes
✔ Handle exceptions when accessing files
✔ Keep file paths organized
Conclusion
File handling in Python is essential for storing, retrieving, and processing data. Mastering it allows you to work with files effectively in real-world applications.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/