File Handling
File handling involves reading from and writing to files, enabling programs to interact with external data storage. Python provides built-in functions and methods to manage files efficiently, with support for text, binary, and various file formats.
| Mode | Description |
|---|---|
'r' |
Read (default). Error if file doesn't exist. |
'w' |
Write. Creates file or overwrites existing. |
'a' |
Append. Adds to end; creates if not exist. |
'x' |
Exclusive creation. Error if file exists. |
'r+' |
Read and write. Error if file doesn't exist. |
'w+' |
Read and write. Creates/overwrites file. |
'rb', 'wb', etc. |
Binary mode (e.g., for images, videos). |
File Operations
Opening File
file = open("example.txt", "r")
file.close()
##Using with statement
with open("example.txt", "r") as file:
content = file.read()
# File is automatically closed after the block
Reading File
a) Read Entire File
with open('example.txt', 'r') as file:
content = file.read()
print(content)
b) Read Line by Line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
c) Read Specific Amount
with open('example.txt', 'r') as file:
chunk = file.read(10)
print(chunk)
Writing to File
a) Write New Content
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
b) Append
with open('example.txt', 'a') as file:
file.write("\nNew line appended")
Binary File Handling
For non-text files.
with open('image.jpg', 'rb') as file:
binary_data = file.read()
with open('image_copy.jpg', 'wb') as file:
file.write(binary_data)
CSV File Handling
Working with CSV files.
import csv
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
Key Features
- Multiple file modes
- Automatic closing
- Text and binary support
- Error handling
Best Practices
- Use `with` statement
- Handle exceptions
- Specify encoding
- Check file existence