Python

How to use python csv writer

In this blog, we will see how we can use the python csv writer to write the list data to csv.

1. Method: Python write a list to CSV

In the first method, we will write a list to a CSV file using the csv.writer().

    import csv
Details = ['Name', 'class', 'Year', 'Subject','Grade']  
rows = [ ['Susjan', '2nd', '2020', 'Physics','A'],
        ['John', '3rd', '2022', 'Chemistry','B'],
        ['Sam', '4th', '2021', 'Math','A']]
with open('studentData.csv', 'w') as f:
    write = csv.writer(f)
    write.writerow(Details)
    write.writerows(rows)

Output:

Name,class,Year,Subject,Grade
Susjan,2nd,2020,Physics,A
John,3rd,2022,Chemistry,B
Sam,4th,2021,Math,A

Line 1: We import the CSV module.

Line 2 to 3: We created two lists of details and rows. The details list will represent the names of the columns, and the rows lists will represent each column’s data.

Line 6 to 9: We open a file studentData.csv as a write mode (‘w’) to write the file. Now, we created an object write using the csv.writer(f). First, we write the names of the column of the csv using the details list. After writing the column names of the csv, we use the write.writerows() and pass into them the rows list as a parameter to write each of the lists as a row.

2. Method: Python write a list to CSV row

In this method, we are going to write the CSV row using the csv.writer(). The program details how to use this method to write rows of the csv given below:

    import csv
data = [['a'], ['b'], ['c'],['d']]
file = open('alphabet.csv', 'w+',newline ='')
with file:    
    write = csv.writer(file)
    write.writerows(data)

Ouput:

a
b
c
d

Line 1: We import the CSV module.

Line 2: We created one list of data which elements are also a list. Each sublist will be treated as a separate row.

Line 3 to 6: We open a file alphabet.csv as a write mode (‘w’) to write the file. We are also using the newline attribute, which helps to get the value into the new row. Now, we created an object to write using the csv.writer(file). To write each of the lists as a row, we use the write.writerows() and pass the data list as a parameter into them.

From the output, we can see that all sublists have been written as a new row.

3. Method: Python write a list to CSV header

In this method, we are going to write the header of the CSV file.

    import csv
list = [[ 'New York', 'USA','A'],['Toronto', 'CANADA', 'A'],['Bejing','CHINA','B']]
with open('header.csv','w') as f:
    writer = csv.writer(f)
    writer.writerow(['City', 'Country', 'Rank'])
    writer.writerows(list)

Output:

City,Country,Rank

Line 1: We import the CSV module.

Line 2 to 3: We created one list of data in which elements are also a list. Each sublist will be treated as a separate row.

Line 4 to 7: We open a file rank.csv as a write mode (‘w’) to write the file. Now, we created an object to write using the csv.writer(f). First, we write the names of the column of the csv using the writerow ([‘City’, ‘Country’, ‘Rank’]).

The output shows that we have successfully written the header of the csv file.

4. Method: Python write a list tuple elements to a csv

This method will show how we can write the elements tuple type inside of a list to a csv.

    import csv
items = [(('A', 'Sam'), 25), (('B', 'Rakesh'), 23), (('C', 'Kaira'), 42)]
with open('tuple.csv', 'w') as f:
    write = csv.writer(f)
    write.writerows(items)

Output:

"('A', 'Sam')",25
"('B', 'Rakesh')",23
"('C', 'Kaira')",42

Line 1: We import the CSV module.

Line 2: We created a list of items, and each element of the list is a tuple type.

Line 3 to 5: We open a file tuple.csv as a write mode (‘w’) to write the file. Now, we created an object to write using the csv.writer(f). To write each of the list elements (tuple) as a row, we use the write.writerows () and pass into them the items list as a parameter.

5. Method: Python append a list to a csv

This method will show how we can append any new data to a csv using the python writer.

    import csv
with open('result.csv','a') as f:
    writer = csv.writer(f)
    writer.writerow(['city','New York'])

Output:

"('A', 'Sam')",25
"('B', 'Rakesh')",23
"('C', 'Kaira')",42
city,New York

Line 1: We import the CSV module.

Line 2: We open the result.csv file in the append mode because we want to add some more data to the existing csv file.

Line 3 to 4: Now, we created an object to write using the csv.writer(f). To write each of the list elements as a row, we use the write.writerows () and pass into them the items list as a parameter. But as now we have only one list, we will use the writerow() method only.

From the output, we can see that we append the new data successfully to an existing csv file.

6. Method: Python append a list to a csv

    import csv
from itertools import zip_longest
item_1 = ['A', 'B', 'C', 'D']
item_2 = [1,2,3,4]
data = [item_1, item_2]
export_data = zip_longest(*data, fillvalue = '')
with open('item_zip.csv', 'w', encoding="ISO-8859-1", newline='') as file:
      write = csv.writer(file)
      write.writerow(("item_1", "item_2"))
      write.writerows(export_data)

Output:

item_1,item_2
A,1
B,2
C,3
D,4

Line 1 and 2: We import the CSV module and zip_longest. This module is used for iteration in sequence order.

Line 3 to 5: We created two lists item_1 and item_2, for the data iteration. We then combine both lists into a single list and name that list to data.

Line 6: We then call the method zip_longest to parallel iterate two lists.

Line 7 to 10: We open a file item_zip.csv as a write mode (‘w’) to write the file. Now, we created an object to write using the csv.writer(f). First, we write the names of the column of the csv, and after writing that, to write each of the lists as a row, we use the write.writerows() and pass into them the rows list (export_data) as a parameter.

The output shows that we have successfully written our zip data into the csv file.

7. Method: Write CSV File with custom Pipe Delimiter

In this method, we will use the pipe delimiter (‘|’) instead of the comma. The below program will explain how we can use the pipe delimiter in our code.

    import csv
Details = ['Name', 'class', 'Year', 'Subject','Grade']  
rows = [ ['Susjan', '2nd', '2020', 'Physics','A'],
        ['John', '3rd', '2022', 'Chemistry','B'],
        ['Sam', '4th', '2021', 'Math','A']]
with open('pipe_delimiter.csv', 'w') as f:
    write = csv.writer(f,delimiter='|')
    write.writerow(Details)
    write.writerows(rows)

Output:

Name|class|Year|Subject|Grade
Susjan|2nd|2020|Physics|A
John|3rd|2022|Chemistry|B
Sam|4th|2021|Math|A

Line 1: We import the CSV module.

Line 2 to 3: We created two lists of details and rows. The details list will represent the names of the columns, and the rows lists will represent each column’s data.

Line 6 to 9: We open a file studentData.csv as a write mode (‘w’) to write the file. Now, we created an object to write using the csv.writer(f). We also add one extra attribute delimiter into the csv.writer() method along with the f. First, we write the names of the column of the csv using the details list. After writing that, we use the write.writerows() and pass the rows list as a parameter to write each of the lists as a row.

The output shows that our csv file data is separated from the pipe delimiter instead of the comma.

8. Method: Write CSV File with custom quoting character

In this method, we will use some custom quoting characters while saving the data to csv format. For that, we have to use the quoting=csv.QUOTE_NONNUMERIC attribute and quotechar as shown in the below program.

    import csv
Details = ['Name', 'class', 'Year', 'Subject','Grade']  
rows = [ ['Susjan', '2nd', '2020', 'Physics','A'],
        ['John', '3rd', '2022', 'Chemistry','B'],
        ['Sam', '4th', '2021', 'Math','A']]
with open('quote.csv', 'w') as f:
    write = csv.writer(f,quoting=csv.QUOTE_NONNUMERIC,
                        delimiter=';', quotechar='*')
    write.writerow(Details)
    write.writerows(rows)

Ouput:

*Name*;*class*;*Year*;*Subject*;*Grade*
*Susjan*;*2nd*;*2020*;*Physics*;*A*
*John*;*3rd*;*2022*;*Chemistry*;*B*
*Sam*;*4th*;*2021*;*Math*;*A*

Line 1: We import the CSV module.

Line 2 to 3: We created two lists of details and rows. The details list will represent the names of the columns, and the rows lists will represent each column’s data.

Line 6 to 9: We open a file studentData.csv as a write mode (‘w’) to write the file. Now, we created an object to write using the csv.writer(f). We also add one extra attribute quoting and quotechar into the csv.writer() method along with the f. First, we write the names of the column of the csv using the details list. After writing that, we use the write.writerows() and pass the rows list as a parameter to write each of the lists as a row.

The output shows that our csv file data is now quoted with the custom quotechar.

9. Method: Write CSV File using csv.DictWriter()

We can also write the csv file using the DictWriter () method. So in this program, we will see how we can use the DictWriter () method to write the csv file.

    import csv

with open('dictwriter.csv', 'w', newline='') as file:
    fieldnames = ['A', 'B']
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'A': 'Magnus Carlsen', 'B': 28770})
    writer.writerow({'A': 'Fabiano Caruana', 'B': 28222})
    writer.writerow({'A': 'Ding Liren', 'B': 28001})

Output:

A,B
Magnus Carlsen,28770
Fabiano Caruana,28222
Ding Liren,28001

Line 1: We import the module csv.

Line 3: We open the file dictwriter.csv in the write mode.

Line 4 and 5: In this dictwriter () method, we must define the keys in the list and pass while creating the writer object, as shown in line number 5. The fieldnames are in the same sequence in which we want to write the csv file.

Line 8 to 10: We pass all the data to the writerow in the form of the dict (key and value).

Conclusion:

In this article, we have seen different ways to use the csv.writerow () methods. We have seen how we can write the whole list to a csv. We have also seen how we can write the tuples inside of the list to a csv. Then we have seen some interesting methods like custom delimiter of the csv.

About the author

Shekhar Pandey