25. File Handling and CSV Operations in Python
Level: AdvancedDuration: 34m
Working with Text Files
Python provides built-in functions to work with text files. You can open files in read (`r`), write (`w`), append (`a`), or read/write (`r+`) modes.
python
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, Python!\n')
file.write('This is a text file example.')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)Appending Data to Files
You can add new content without overwriting existing data using the append mode.
python
with open('example.txt', 'a') as file:
file.write('\nAppended line!')Working with CSV Files
CSV (Comma-Separated Values) files store tabular data. Python's `csv` module makes reading and writing CSVs simple.
Reading CSV Files
python
import csv
with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)Writing CSV Files
python
import csv
data = [
['Name', 'Age', 'Email'],
['Alice', 30, 'alice@example.com'],
['Bob', 25, 'bob@example.com']
]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)Best Practices
- Always use `with open(...)` to automatically close files.
- Use `newline=''` when writing CSVs to prevent blank lines on Windows.
- Validate CSV data before processing to avoid runtime errors.
- Organize file operations into functions for reusable code.
💡 Tip: CSV files are great for simple datasets, but for large datasets, consider using pandas for faster and more flexible data handling.
Mini Project Step
Create a CSV file `contacts.csv` with columns: name, phone, and email. Write Python code to add new contacts, read all contacts, and update or delete a contact. Try to implement this using both `csv.reader`/`csv.writer` and Python lists for practice.