Code Examples – Write A List To CSV Using Python

Do you have a list of data that you want to write on a CSV file using Python? In this article, Learn to write a List to CSV using Python in various ways.

You can use the CSV library[1] in Python that allows you to write the values from any kind of datasets you have to the CSV file format. To write any data on the CSV file using Python you need to follow below basic bullet points.

  • Import the CSV Library in your Python Program.
  • Make Sure you have the List or Data you want to write ready.
  • Use open function to create or open and existing CSV file.
  • Now use the writerows function from the CSV library to write the values to CSV File.

In plain text documents, Comma Separated Values (CSV) files are a type of plain text document in which tabular information is organized in a specific manner. A CSV file is a text file with a defined boundary that employs a comma to denote the separation of values.

Let us see in the below code examples and various ways you may require to add the data to the CSV File.

1. Write A List To CSV File Row Wise

You can easily write data from a list to rows in a CSV file. In the CSV library, the function writerow(row) or writerows(rows) is used to write the data to the rows in CSV File. Both functions call the writer object to write the data on the row or rows of the CSV file.

The writerow() function of the writer and DictWriter classes is the most commonly used technique for writing data from a list to a CSV file. Let us see in the below example code, how to write a list to CSV file Row Wise using Python.

1.1 Write A List To CSV Row by Row [Different Rows and Same Column] or Line by Line

If you are going to use the function writerow() then you can write only one item to the row in CSV. And also you will have to make sure that you are itemizing the elements with square bracket as shown in the below code.

#importing CSV library
import csv

#Creating List Of Values
listToWrite = ["2021", "Data", "You", "Are", "Watching"]

with open("newCSV.csv", 'w') as csvFile:
    getWriter = csv.writer(csvFile, dialect='excel')
    #Writing Values to Row one by One
    for item in listToWrite:
        getWriter.writerow([item])

Output:

2021

Data

You

Are

Watching

As you can see from the above code, I was able to write the list data to the different rows one by one using the writer object with writerow() function. You have to itemize the item using the square bracket while writing the data from the list. I haven’t opened it in Excel but if you open it in Excel it will be written in each row of the first column.

Write A List To CSV Using Python

1.2 Write A List To CSV At Once Row Wise [Single Row and Different Column].

The second method to writing a list to CSV can be writing all the data in the list at once to the row of the CSV file. In this code example, I will show you how using the writerow() function you can write all the data to the CSV rows at once and it will not require you to write any For loop.

#importing CSV library
import csv

#Creating List Of Values
listToWrite = ["2021", "Data", "You", "Are", "Watching"]

with open("newCSV.csv", 'w') as csvFile:
    getWriter = csv.writer(csvFile, dialect='excel')
    #Writing Values to Row at Once
    getWriter.writerow(listToWrite)

Output:

2021,Data,You,Are,Watching

As you can see from the above code, I was able to write the list data at once to a single row using the writerow() function. In this case, the column for each data is different but the row remains the same.

1.3 Append A List To CSV Using WriteRow Using Python

You can append a list of data to the existing CSV by opening the CSV in ‘a+’ mode, which suggests that you are opening the file to read and append values to it. And if the file does not exist it will create a new file for you and add those list values to it.

Let us see in the below example code how to append a list to CSV File using writerow() function in Python.

#importing CSV library
import csv

#Data to be Appended
listToWrite = ['3', 'Adam', 'ASU', 'PHD']

#Opening the File in Reading and Appending Mode
with open("newCSV.csv", 'a+') as csvFile:
    #Using DictWriter
    getWriter = csv.writer(csvFile, dialect='excel')
    #Writing Values to Row at Once with Different Character
    #At Different Columns
    getWriter.writerow(listToWrite)

Output:

Write A List To CSV Using Python

So using the writerow() function and opening the CSV file in ‘a+’ mode I was able to append a list of data to the CSV file successfully.

2. Write A List To CSV Using DictWriter in Orgranized Way

Now if you have a List of Data that you want to write to CSV in an organized way then you will have to use the DictWriter. DictWriter provides you the feature to name all the columns headers to a default value and then you can write the data for each column respectively making the data in an organized form.

Let us see in the below example code the usage of DictWriter to write a list to CSV in Python.

#importing CSV library
import csv

#Creating List Of Values
listToWrite = ['1', 'John David', 'CMU', 'MS']

#Creating the List of Header for Column
listOfHeader = ['ID', 'Name', 'University', 'Course']

#creating a Dict Object with List Data and Header Data
dictToWrite = dict(zip(listOfHeader, listToWrite))

with open("newCSV.csv", 'w') as csvFile:
    #Using DictWriter
    getWriter = csv.DictWriter(csvFile, fieldnames = listOfHeader, dialect='excel')
    #Writing Values to Row at Once with Different Character
    #At Different Columns
    getWriter.writeheader()
    getWriter.writerow(dictToWrite)

Output:

ID,Name,University,Course
1,John David,CMU,MS

As you can see in the above code, I was able to zip the header list and list data and typecast it to the dictionary so that I can write that data to the CSV file using the DictWriter. DictWriter allows you to organize the data and help you maintain the information in a proper way.

2.1 Append A List Data To CSV File Using Python

Now if you want to append a List data to your existing file then you can use the similar methods discussed above but you are required to open the CSV file with ‘a+’ notation that denotes that you want to open the file for reading and append values to it. If the file does not exist it will be created automatically for the first time.

Let us see in the below example code how to append a List data to a CSV file using Python.

#importing CSV library
import csv

#Data to be Appended
listToWrite = ['2', 'Paige', 'UCI', 'UG']

#Creating the List of Header for Column
listOfHeader = ['ID', 'Name', 'University', 'Course']

#creating a Dict Object with List Data and Header Data
dictToWrite = dict(zip(listOfHeader, listToWrite))

with open("newCSV.csv", 'a+') as csvFile:
    #Using DictWriter
    getWriter = csv.DictWriter(csvFile, fieldnames = listOfHeader, dialect='excel')
    #Writing Values to Row at Once with Different Character
    #At Different Columns
    getWriter.writerow(dictToWrite)

Output:

Write A List To CSV Using Python

As you can see in the above code, I was able to append the list data using the zip and typecast the data to dictionary values and then using the DictWriter to append the values. Since I have executed the program 2 times it has appended the same value two times.

3. Using Pandas To Write A List To CSV In Python

You can use the Panda library as well in Python to write a list data to the CSV file. Using the CSV writer takes a lot of time if you are having a big CSV file to append data to. And hence to optimize your runtime Pandas library comes into the picture.

But before getting started with Pandas Library you need to make sure that Pandas are installed in your system.

#importing Pandas
import pandas

#Creating List to be Appended or Added
#To the CSV File
listData = [['1', 'Sheldon', 'Cal', 'PHD']]

columnHeader = ['ID', 'Name', 'University', 'Degree']

#Creating Pandas Object
pd = pandas.DataFrame(listData, columns=columnHeader)

#Writing Data to CSV File
pd.to_csv("newCSV.csv", index=False)

Output:

Write A List To CSV Using Python

As you can see in the above code, I was able to add the new data to the CSV file using Pandas library, to add new data you need to keep the list data with a list of data in each index. And then using DataFrame you need to specify what are your default column list data and then you will be able to add the data to the CSV File.

To append values to the CSV File using Pandas Library you will require to use the mode as ‘a’ in the to_csv() function. Let us see in the below example code how to append a list of data to CSV using Pandas Library.

#importing Pandas
import pandas

#Creating List to be Appended or Added
#To the CSV File
listData = [['3', 'John', 'ASU', 'MS']]

columnHeader = ['ID', 'Name', 'University', 'Degree']

#Creating Pandas Object
pd = pandas.DataFrame(listData, columns=columnHeader)

#Writing Data to CSV File and Setting Mode to Append
pd.to_csv("newCSV.csv", index=False, header=False, mode='a')

Output:

Write A List To CSV Using Python

Using the mode set in the above code I was able to easily append the data to the existing CSV file. It is better to use Pandas instead of NumPy that I am going to discuss next.

4. Using NumPy To Write A List To CSV in Python

Another library that supports writing a list of data to CSV files is the NumPy library. In this, you need to specify the list data as NumPy array data and then you can use the savetxt() function to add the list data to the CSV file.

Let us see in the below code example how to write a list data to CSV File line by line using NumPy in Python.

#importing NumPy
import numpy as np

#Creating List to be Added
#To the CSV File
listData = ['4', 'John', 'ASU', 'MS']

columnHeader = ['ID', 'Name', 'University', 'Degree']

#Creating NumPy Object and Array it to List Data
dataToAdd = np.asarray([listData])

#Writing Data to CSV File.
np.savetxt('newCSV.csv', dataToAdd, delimiter=',', fmt='%s' )

Output:

4,John,ASU,MS

As you can see in the above code, using NumPy I was able to save the list data to the CSV file. You need to make sure that you use fmt as %s if you are trying to add string values to the CSV file else you may encounter errors while executing the program.

Wrap Up

I hope you were able to learn how to write a list to CSV file in Python in various ways. I have discussed more than 8 methods above that you can use to resolve this problem statement.

Let me know in the comment section if you have any better solution than the one is discussed above, I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Code Example: Loop Back To The Beginning Of A Program
  2. How To Do Nothing In An If Statement Python
  3. Code Example: Remove The First Item From List Python
  4. 4 Ways To Loop Through List With Index Using Python
  5. Code Examples: Multiply In Python
  6. How To Join Words In a List Using Python Code Example
  7. Python Code Example: How To Find Element in a List in 6 Way
  8. How To Test For An Empty Object In JavaScript

Leave a Comment