Writing to CSV in Python

turned-on gray laptop computer

To write to CSV in Python, use Python’s csv module.

For example, let’s write a list of strings into a new CSV file:

import csv

data = ["This", "is", "a", "Test"]

with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

As a result, you see a file called example.csv in the current folder.

There is a lot more to cover when it comes to writing CSV files in Python. Let’s jump into the details and see some useful examples.

Writing to CSV in Python in Detail

CSV or comma-separated values is a text file. It consists of comma-separated data.

CSV is a useful data format for applications to transfer data. The CSV is a simple lightweight text file. This makes it a perfect fit for sending and receiving data in an efficient way.

For example, you can retrieve data from a database as a CSV. Or you can add a new entry to a database using CSV format.

Here is an example of how CSV data looks like:

CSV Example in Python

However, in this guide, I’m using Mac’s built-in CSV viewer. Thus the CSV data looks more like this:

CSV Example in Python

In the introduction, you saw a simple example of how to write a piece of data into a CSV file. Let’s now take a deeper look at how to write CSV files with Python.

The 4 Steps to Writing a CSV in Python

To write a CSV file in Python, use these four steps:

  1. Open a CSV file in the write mode. This happens using the open() function. Give it the path of the file as the first argument. Specify the mode as the second argument ('r' for read and 'w' for write).
  2. Create a CSV writer object for the file. To do this, create a csv module’s writer() object, and pass the opened file as its argument.
  3. Write data to the CSV file. Use the writer object’s writerow() function to write data into the CSV file.
  4. Close the CSV file using the close() method of a file.

Here is an example that illustrates this process:

import csv

# 1.
file = open('test.csv', 'w')

# 2.
writer = csv.writer(file)

# 3.
data = ["This", "is", "a", "Test"]
writer.writerow(data)

# 4.
file.close()

This piece of code creates a file called test.csv into the current folder.

The open() function opens a new file if the file specified does not exist. If it does, then the existing file is opened.

The Shorthand Approach

To make writing to CSV a bit shorter, use the with statement to open the file. This way you don’t need to worry about closing the file yourself.

import csv

# 1. step
with open('PATH_TO_FILE.csv', 'w') as file:
    # 2. step
    writer = csv.writer(file)
    # 3. step
    data = ["This", "is", "a", "Test"]
    writer.writerow(data)

Doing it this way, there are only three steps to take.

How to Write Non-ASCII Characters to a CSV in Python

By default, you cannot write non-ASCII characters to a CSV file. To overcome this, specify the character encoding in the open() call as the third argument.

with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")

The rest of the process follows the steps you learned earlier.

Now you have a basic understanding on how to write a CSV file using Python. Let’s next see some examples.

Examples

Let’s create an example CSV file that consists of student data.

To structure the data, create a header for the students. Then define the actual data. Then follow the four (or three using with statement) steps to writing the data into a CSV file.

Here is the code:

import csv

# Define the structure of the data
student_header = ['name', 'age', 'major', 'minor']

# Define the actual data
student_data = ['Jack', 23, 'Physics', 'Chemistry']

# 1. Open a new CSV file
with open('students.csv', 'w') as file:
    # 2. Create a CSV writer
    writer = csv.writer(file)

    # 3. Write data to the file
    writer.writerow(student_header)
    writer.writerow(student_data)

This creates students.csv file into the folder you are currently working in. The new file looks like this:

CSV Example in Python

Let’s say you want to write more than one line of data into your file. For instance, you may have a list of students instead of just one.

To write multiple lines of data into a CSV, use the writerows() method.

Here is an example of writing multiple students into a CSV file:

import csv

student_header = ['name', 'age', 'major', 'minor']

student_data = [
    ['Jack', 23, 'Physics', 'Chemistry'],
    ['Sophie', 22, 'Physics', 'Computer Science'],
    ['John', 24, 'Mathematics', 'Physics'],
    ['Jane', 30, 'Chemistry', 'Physics']
]

with open('students.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(student_header)

    # Use writerows() not writerow()
    writer.writerows(student_data)

This results in a new CSV file that looks like this:

CSV Example in Python

How to Write a Dictionary to a CSV in Python

What if the data you want to write into a CSV is not a list at all? For example, you can have a dictionary that represents student objects.

In this case, use the csv module’s DictWriter object. The process is similar to using the regular CSV writer.

To write dictionary data into a CSV file:

  • Use a csv module’s DictWriter object and specify the field names in it.
  • Use writeheader() method to set up the header into the CSV file.
  • use the writerows() method to write the dictionary data into the file.

Here is an example:

import csv

student_header = ['name', 'age', 'major', 'minor']

student_data = [
    {'name': 'Jack', 'age': 23, 'major': 'Physics', 'minor': 'Chemistry'},
    {'name': 'Sophie', 'age': 22, 'major': 'Physics', 'minor': 'Computer Science'},
    {'name': 'John', 'age': 24, 'major': 'Mathematics', 'minor': 'Physics'},
    {'name': 'Jane', 'age': 30, 'major': 'Chemistry', 'minor': 'Physics'}
]

with open('students.csv', 'w') as file:
    # Create a CSV dictionary writer and add the student header as field names
    writer = csv.DictWriter(file, fieldnames=student_header)
    # Use writerows() not writerow()
    writer.writeheader()
    writer.writerows(student_data)

Now the result is the same CSV file as in the earlier example:

CSV Example in Python

Conclusion

CSV or comma-separated values is a commonly used file format. It consists of values that are usually separated by commas.

To write into a CSV in Python, you need to use the csv module with these steps:

  1. Open a CSV file in the write mode.
  2. Create a CSV writer object.
  3. Write data to the CSV file.
  4. Close the CSV file.

Here is a practical example.

import csv

data = ["This", "is", "a", "Test"]

with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *