CSV (Comma Separated Values) files are widely used for storing tabular data. Python provides the csv
module, which makes it easy to read from and write to CSV files. In this article, we will explore how to read and write CSV files using the csv
module with examples.
csv
ModuleBefore working with CSV files, we need to import Python's built-in csv
module. The csv
module provides functionality for reading and writing CSV files, and it works seamlessly with Python's file handling system.
import csv
The csv.reader()
function allows you to read CSV files. It returns an iterator, which can be used to iterate over each row in the file. Each row is returned as a list of values.
import csv # Open the CSV file in read mode with open('data.csv', 'r') as file: csv_reader = csv.reader(file) # Iterate over each row and print it for row in csv_reader: print(row)
In this example, the CSV file data.csv
is opened, and the rows are read using csv.reader()
. Each row is printed as a list of values.
If your CSV file contains a header (i.e., the first row contains column names), you can use the csv.DictReader()
function. This will allow you to access the data by column name instead of by index.
csv.DictReader()
to Read a CSV Fileimport csv # Open the CSV file in read mode with open('data.csv', 'r') as file: csv_reader = csv.DictReader(file) # Iterate over each row and print the values using column names for row in csv_reader: print(row['Name'], row['Age'], row['City'])
In this example, csv.DictReader()
is used to read the CSV file with headers. The values are accessed by column name (e.g., row['Name']
, row['Age']
, and row['City']
).
To write data to a CSV file, you can use the csv.writer()
function. This function allows you to write rows to a CSV file in the form of lists or tuples.
import csv # Open the CSV file in write mode with open('output.csv', 'w', newline='') as file: csv_writer = csv.writer(file) # Write the header (optional) csv_writer.writerow(['Name', 'Age', 'City']) # Write some rows of data csv_writer.writerow(['John Doe', 30, 'New York']) csv_writer.writerow(['Jane Smith', 25, 'Los Angeles'])
In this example, the file output.csv
is created and opened in write mode. The header is written first using csv_writer.writerow()
, followed by two rows of data. The newline=''
argument is used to prevent blank lines between rows when writing to a CSV file.
If you have data stored as dictionaries, you can use the csv.DictWriter()
function to write rows to a CSV file. This allows you to write data with field names directly from a dictionary.
csv.DictWriter()
to Write to a CSV Fileimport csv # Open the CSV file in write mode with open('output.csv', 'w', newline='') as file: fieldnames = ['Name', 'Age', 'City'] csv_writer = csv.DictWriter(file, fieldnames=fieldnames) # Write the header csv_writer.writeheader() # Write some rows of data csv_writer.writerow({'Name': 'John Doe', 'Age': 30, 'City': 'New York'}) csv_writer.writerow({'Name': 'Jane Smith', 'Age': 25, 'City': 'Los Angeles'})
In this example, csv.DictWriter()
is used to write a dictionary to the CSV file. The writeheader()
method writes the field names (header), and writerow()
writes the rows of data using dictionaries.
Python's csv
module provides a powerful and easy way to read from and write to CSV files. The csv.reader()
and csv.DictReader()
functions allow you to read CSV files either as lists or dictionaries. The csv.writer()
and csv.DictWriter()
functions allow you to write data to CSV files. By mastering these functions, you can easily handle CSV files in your Python programs.