90. Working with CSV Files
The csv module in Python allows you to easily read and write CSV files. Below are 10 Python code snippets demonstrating common tasks when working with CSV files.
1. Reading a CSV File
Copy
import csv
# Open the CSV file for reading
with open('data.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)This snippet opens a CSV file and prints each row. The csv.reader is used to read the contents of the file.
2. Reading CSV File with Headers
Copy
import csv
# Open the CSV file for reading with headers
with open('data.csv', mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)DictReader reads the CSV into dictionaries using the first row as the keys for the fields, making it easier to access by column name.
3. Writing Data to a CSV File
Copy
This snippet writes a list of lists to a CSV file. writerows writes multiple rows at once.
4. Writing Data with Headers
Copy
DictWriter is used for writing dictionaries into the CSV file, and writeheader() writes the column names.
5. Reading CSV File Line by Line
Copy
This reads and processes each row of the CSV file one at a time, making it memory-efficient for large files.
6. Skipping Header Row in CSV
Copy
The next(reader) skips the first row, which is usually the header row.
7. Handling Comma-Separated Values with Different Delimiters
Copy
If the CSV uses a delimiter other than a comma (like semicolon ;), you can specify it using the delimiter parameter.
8. Writing CSV Data with Custom Delimiter
Copy
You can use a custom delimiter, such as a semicolon ;, when writing to a CSV file.
9. Reading CSV with Encoding
Copy
When reading files with non-ASCII characters, you may need to specify an encoding like utf-8 to avoid encoding errors.
10. Handling Empty Rows in CSV Files
Copy
This ensures that empty rows are skipped by checking if the row is not empty before processing it.
Last updated