CSV (Comma Separated Values) is a popular file format used to store tabular data. Python’s built-in csv
module makes it easy to read and write data in CSV format. In this tutorial, we will cover how to handle CSV files in Python, including reading, writing, and manipulating CSV data.
1. Importing the CSV Module
Before working with CSV files, you need to import Python’s csv
module:
import csv
2. Reading a CSV File
To read a CSV file in Python, you can use the csv.reader()
function. This function returns an iterable object that can be looped through to extract each row of the CSV file.
Example: Reading a CSV File
import csv with open('example.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row)
In this example, we open the CSV file in read mode ('r'
) and use csv.reader()
to read each row. The for
loop prints each row in the CSV file.
3. Reading CSV Files with Headers
If your CSV file contains headers (i.e., the first row is the column names), you can use the csv.DictReader()
function. This function returns each row as a dictionary, where the keys are the column names from the header row.
Example: Reading CSV File with Headers
import csv with open('example_with_headers.csv', 'r') as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(row)
In this example, each row is returned as a dictionary, and you can access each column by name instead of index.
4. Writing to a CSV File
To write data to a CSV file, you can use the csv.writer()
function. If the file already exists, this function will overwrite it by default. You can also use csv.DictWriter()
to write dictionaries to the CSV file, which is especially useful when writing data with headers.
Example: Writing to a CSV File
import csv data = [["Name", "Age", "City"], ["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"], ["Charlie", 35, "Chicago"]] with open('output.csv', 'w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(data)
In this example, we write a list of lists to a CSV file using csv.writer()
. The writerows()
method writes multiple rows at once.
Example: Writing a Dictionary to a CSV File
import csv header = ["Name", "Age", "City"] data = [{"Name": "Alice", "Age": 30, "City": "New York"}, {"Name": "Bob", "Age": 25, "City": "Los Angeles"}, {"Name": "Charlie", "Age": 35, "City": "Chicago"}] with open('output_dict.csv', 'w', newline='') as file: csv_writer = csv.DictWriter(file, fieldnames=header) csv_writer.writeheader() # Write the header csv_writer.writerows(data) # Write the data
Here, we use csv.DictWriter()
to write a list of dictionaries to the CSV file. The writeheader()
method writes the column names from the header list, and writerows()
writes the rows of data.
5. Appending Data to a CSV File
To append data to an existing CSV file, you can open the file in append mode ('a'
) and use the same csv.writer()
or csv.DictWriter()
methods.
Example: Appending to a CSV File
import csv new_data = [["David", 40, "Miami"]] with open('output.csv', 'a', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(new_data)
This example opens the file in append mode and adds a new row to the existing CSV file.
6. Handling CSV Files with Special Characters
When working with CSV files that contain special characters (like commas, quotes, or newlines), you can specify how to handle these characters using the quotechar
and quoting
parameters in the csv.writer()
and csv.reader()
methods.
Example: Handling Special Characters
import csv data = [["Name", "Address"], ["Alice", "1234 Elm St, Springfield"], ["Bob", "5678 Oak St, Los Angeles"]] with open('output_special.csv', 'w', newline='') as file: csv_writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerows(data)
In this example, we use the quotechar='"'
and quoting=csv.QUOTE_MINIMAL
to ensure that values with commas or special characters are properly quoted in the CSV file.
Conclusion
Python makes it easy to handle CSV files with the csv
module. You can read, write, and manipulate CSV data with a few simple functions.