14
Day 14: File Handling
Chapter 14 • Intermediate
45 min
File handling allows you to read from and write to files on your computer. This is essential for storing data permanently and working with external files.
What is File Handling?
File handling is the process of reading data from files or writing data to files. Python makes this easy with built-in functions.
File Operations:
- Reading - Get data from a file
- Writing - Put data into a file
- Appending - Add data to the end of a file
- Creating - Make new files
- Deleting - Remove files
File Modes:
- 'r' - Read mode (default)
- 'w' - Write mode (overwrites existing file)
- 'a' - Append mode (adds to end of file)
- 'x' - Create mode (fails if file exists)
- 'b' - Binary mode (for images, videos)
- '+' - Read and write mode
Best Practices:
- Always close files after use
- Use 'with' statement for automatic file closing
- Handle exceptions when files don't exist
- Use appropriate file modes
- Check file permissions
Hands-on Examples
File Operations
# Write to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a Python file handling example.\n")
file.write("We can write multiple lines.\n")
print("File written successfully!")
# Read from a file
with open('example.txt', 'r') as file:
content = file.read()
print("File content:")
print(content)
# Read line by line
print("\nReading line by line:")
with open('example.txt', 'r') as file:
for line_num, line in enumerate(file, 1):
print(f"Line {line_num}: {line.strip()}")
# Append to a file
with open('example.txt', 'a') as file:
file.write("This line was appended!\n")
print("\nAfter appending:")
with open('example.txt', 'r') as file:
print(file.read())This example shows how to write to a file, read from it, read line by line, and append new content. The with statement automatically closes the file.