Comma Separated Values (CSV) files are widely used to store and exchange tabular data. Python provides a built-in module named csv
that makes it easy to read and write CSV files. In this tutorial, we will explore how to write CSV files in Python using the csv
module.
Prerequisites
Before we start, make sure you have Python installed on your system. You can download the latest version of Python from the official website. Also, make sure to have a basic understanding of Python programming language.
Creating a CSV File
To create a CSV file in Python, we first import the csv
module. The csv
module provides a writer
object that allows us to write CSV files.
import csv
# create a new CSV file
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John Smith', 30, 'New York'])
writer.writerow(['Jane Doe', 25, 'San Francisco'])
In the above code, we first import the csv
module. We then open a new file named data.csv
in write mode using the open()
function. We pass mode='w'
to indicate that we want to write to the file. We also pass newline=''
to ensure that the CSV file is written with the correct line endings.
Next, we create a writer
object using the csv.writer()
function and pass the file object as a parameter. We then write the header row and two data rows using the writerow()
method.
When we run the above code, a new CSV file named data.csv
will be created in the current working directory with the following contents:
Name,Age,City
John Smith,30,New York
Jane Doe,25,San Francisco
Writing Multiple Rows at Once
We can also write multiple rows at once using the writerows()
method. The writerows()
method takes a list of rows, where each row is a list of values.
import csv
# create a new CSV file
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
rows = [
['John Smith', 30, 'New York'],
['Jane Doe', 25, 'San Francisco'],
['Bob Johnson', 45, 'Chicago']
]
writer.writerows(rows)
In the above code, we create a list of rows and pass it to the writerows()
method. Each row is a list of values, and the first row is the header row.
When we run the above code, the data.csv
file will contain the following data:
Name,Age,City
John Smith,30,New York
Jane Doe,25,San Francisco
Bob Johnson,45,Chicago
Writing CSV Files with Different Delimiters
By default, the csv
module uses commas as the delimiter for CSV files. However, we can also specify a different delimiter by passing the delimiter
parameter to the csv.writer()
function.
import csv
# create a new CSV file with a semicolon delimiter
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John Smith', 30, 'New York'])
writer.writerow(['Jane Doe', 25, 'San Francisco'])
In the above code, we create a new CSV file with a semicolon delimiter by passing delimiter=';'
to the csv.writer()
function.
When we run the above code, the data.csv
file will contain the following data:
Name;Age;City
John Smith;30;New York
Jane Doe;25;San Francisco
Writing CSV Files with Quotes
Sometimes, the values in a CSV file may contain commas, which can cause issues when reading the file. To avoid this, we can enclose the values in quotes.
import csv
# create a new CSV file with quoted values
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_ALL)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John Smith', 30, 'New York'])
writer.writerow(['Jane Doe', 25, 'San Francisco, CA'])
In the above code, we enclose all values in quotes by passing quoting=csv.QUOTE_ALL
to the csv.writer()
function. This will ensure that any commas within the values are treated as part of the value and not as a delimiter.
When we run the above code, the data.csv
file will contain the following data:
"Name","Age","City"
"John Smith",30,"New York"
"Jane Doe",25,"San Francisco, CA"
Writing CSV Files with Headers
Headers are important for CSV files as they provide a description of the data in the file. We can write headers in CSV files by using the DictWriter
class from the csv
module.
import csv
# create a new CSV file with headers
with open('data.csv', mode='w', newline='') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'John Smith', 'Age': 30, 'City': 'New York'})
writer.writerow({'Name': 'Jane Doe', 'Age': 25, 'City': 'San Francisco'})
In the above code, we create a DictWriter
object by passing the file object and the field names as parameters. We then write the header row using the writeheader()
method and the data rows using the writerow()
method.
When we run the above code, the data.csv
file will contain the following data:
Name,Age,City
John Smith,30,New York
Jane Doe,25,San Francisco
Conclusion
In this tutorial, we have explored how to write CSV files in Python using the csv
module. We have seen how to create a CSV file, write multiple rows at once, use different delimiters and quotes, and write headers in CSV files. By mastering these techniques, you can easily write CSV files in Python and manipulate data in a tabular format.