Python write a list to CSV

In this Python tutorial, we will learn the Python write list to CSV, and also we will cover these topics:

  • Python write a list to CSV row
  • Python write a list to CSV header
  • Python write a list to CSV pandas
  • Python write a list to CSV numpy
  • Python write a list to CSV newline
  • Python write a nested list to CSV
  • Python write a list of list to CSV
  • Python append a list to CSV
  • Python write a list to CSV column

Python write a list to CSV

Here, we can see write a list to csv in python

  • In this example, I have imported a module called csv and declared a variable as details.
  • And another variable called rows as rows = [ [‘sushma’, ‘2nd’, ‘2023’, ‘Physics’], [‘john’, ‘3rd’, ‘2022’, ‘M2’], [‘kushi’, ‘4th’, ‘2021’, ‘M4’]] and then to open the csv file, I have used with open(‘student.csv’, ‘w’) as f: is used to open the file.
  • The student.csv is the name of the file, the “w” mode is used to write the file, to write the list to the CSV file write = csv.writer(f), to write each row of the list to csv file writer.writerow() is used.

Example:

import csv 
Details = ['Name', 'class', 'passoutYear', 'subject']  
rows = [ ['sushma', '2nd', '2023', 'Physics'],  ['john', '3rd', '2022', 'M2'],  ['kushi', '4th', '2021', 'M4']] 
with open('student.csv', 'w') as f: 
    write = csv.writer(f) 
    write.writerow(Details) 
    write.writerows(rows) 

You can see the list as the output in the below screenshot.

Python write a list to CSV
Python write a list to CSV

Python write a list to CSV row

Here, we can see how to write a list to csv row in python.

  • In this example, I have imported a module called csv and called variable data and assigned data = [[‘1’], [‘3’], [‘5’],[‘7’]] and created a file as odd.csv using “w+” mode to write the file.
  • And newline = ‘ ‘ is used to get the values in the newline. The csv.writer(file) is used to write all the data from the list to the CSV file, the write.writerows is used to write all the rows to the file.

Example:

import csv 
data = [['1'], ['3'], ['5'],['7']] 
file = open('odd.csv', 'w+', newline ='') 
with file:     
    write = csv.writer(file) 
    write.writerows(data) 

We can see the output in the row format. You can refer to the below screenshot for the output

Python write a list to CSV row
Python write a list to CSV row

Python write a list to CSV header

Here, Now we can see how write a list to csv header in python.

  • In this example, I have imported a module called csv and taken a variable as list. And then to open the file, I have used with open(‘result.csv’,’w’) as f.
  • The result.csv is the name of the file, the csv writer is the function used to write the list to CSV.
  • To write the rows of the list to the CSV file, I have used writer.writerow([‘marks’, ‘total’, ‘result’]).
  • Again writerows() method is used to write the list header also, ‘marks’, ‘total’, ‘result’ is the list of header.

Example:

import csv
list = [['20+30', '50', 'pass'],['10+12', '33', 'fail']]
with open('result.csv','w') as f:
    writer = csv.writer(f)
    writer.writerow(['marks', 'total', 'result'])
    writer.writerows(list)

In the below screenshot, you can see the list along with the header

Python write a list to CSV header
Python write a list to CSV header

Python write a list to CSV pandas

Here, we can see how to write a list csv using pandas in python.

  • In this example, I have imported a module called pandas as pd and I have taken a variable as name.
  • And then declared a dictionary and assigned key and value pair as dictionary = {‘name’: name, ‘subjects’: subjects, ‘marks’: marks}.
  • The data frame is 2 dimensional tabular with tabular columns of potentially different types.
  • The dataframe.to_csv(‘name.csv’) is used to write the data from the list to the CSV file.

Example:

import pandas as pd  
name = ["sonu", "monu"] 
subjects= ["Maths", "English"]
marks = [45, 65,] 
dictionary = {'name': name, 'subjects': subjects, 'marks': marks}  
dataframe = pd.DataFrame(dictionary) 
dataframe.to_csv('name.csv')

You can refer to the below screenshot for the output:

dict
Python write a list to CSV pandas

Python write a list to CSV numpy

Here, we can see how to write a list to csv using numpy in python

  • In this example, I have imported a module called numpy as np and taken a variable as rows.
  • The np.savetxt() method is used to write and save the list to the CSV file, the student .csv is the name of the file, and the delimiter is used and fmt = %s is the place holder.

Example:

import numpy as np 
rows = [ ['Sonu', 'maths', '45'],  
         ['Monu', 'english', '25'],  
         ['Ammu', 'hindi', '35']] 
np.savetxt("student.csv",rows, delimiter =" ",  fmt ='% s') 

The list can be seen as the output, you can refer to the below screenshot for thr output:

Python write a list to CSV numpy
Python write a list to CSV numpy

Python write a list to CSV newline

Now, we can see how to write a list to csv with newline in python

  • In this example, I have imported a module called CSV and I have taken a variable as Even_list.
  • def write_to_csv(Even_list) is used and then to open the file with open(‘even.csv’, ‘w’, newline=”) as csvfile.
  • The even.csv is the name of the file and to get the list in a new separate line, the newline is used as newline=’ ‘, the writer.writerows is used to write each row of the list to the CSV file.
  • The write_to_csv is used to write all the content.

Example:

import csv
Even_list= ['2','4','6','8']
def write_to_csv(Even_list):
     with open('even.csv', 'w', newline='') as csvfile:
         writer = csv.writer(csvfile)
         writer.writerows(Even_list)
write_to_csv(Even_list)  

You can refer to the below screenshot for the output:

Python write a list to CSV newline
Python write a list to CSV newline

Python write a nested list to csv

Now, we can see how write nested list to csv in python

  • In this example, I have imported a module called csv and taken a variable items.
  • To open the file, I have used with open(‘fruits.csv’, ‘w’) as f. The write.writerrows(items) is used to write each row of the list to CSV file.

Example:

import csv 
items = [(('fruits', 'apple'), 25), (('vegetables', 'tomato'), 23), (('chocolate', 'kitkat'), 42)]
with open('fruits.csv', 'w') as f: 
    write = csv.writer(f) 
    write.writerows(items)

We can see the nested list as the output in the below screenshot.

Python write a nested list to csv
Python write a nested list to csv

Python write a list of list to CSV

Here, we can see how to write a list of list to csv in python

  • In this example, I have imported module called csv and taken a variable as data.
  • To open the file I have used with open(“student.csv”, “w”, newline=”) as f. The student.csv is the name of the file, and a newline is used.
  • The writer = csv.writer(f) is used to write the data to the csv file, the writer.writerows(data) is used to write each row to the csv file.

Example:

import csv
data = [['name','sonu'],['age','6'],['gender','male']]
with open("student.csv", "w", newline="") as f:
   writer = csv.writer(f)
   writer.writerows(data)

In the below screenshot you can see the output:

Python write a list of list to CSV
Python write a list of list to CSV

Python append a list to CSV

Here, we can see how to append a list to an already existing csv file in python

  • In this example, I have imported a module called CSV to append the list, I have opened the already existing file as with open(‘result.csv’, ‘a’) as f. The result.csv is the name of the file.
  • The mode “a” is used to append the file, and writer = csv.writer(f) is used to write all the data from the list to a CSV file.
  • The writer.writerow is used to write each row of the list to a CSV file. The [‘grade’,’B’] is the new list which is appended to the existing file.

Example:

import csv
with open('result.csv','a') as f:
    writer = csv.writer(f)
    writer.writerow(['grade','B'])
  

We can see the appended new list in the output, [‘grade’,’B’] is the new list. You can refer to the below screenshot for the output.

Python append a list to CSV
Python append a list to CSV

Python write a list to CSV column

Now, we can see how to write a list to csv column in python

  • In this example, I have imported a module called CSV and from itertools, zip_longest module is imported. This module is mainly used for iterating it, and it prints the value of iterables in the sequence format.
  • I have taken 2 variables as item1 and item2, the values of these two variables are assigned in another variable called data.
  • To move the data from the file and to fill the values, I have used export_data = zip_longest(*data, fillvalue = ”).
  • And opened the file with file name items.csv with “w” mode to write the file and the values are encoded and then to write the data to the CSV file, I have used write = csv.writer(file).
  • The write.writerow() is used to write all the rows of data to the CSV file.

Example:

import csv
from itertools import zip_longest
item1 = ['toys', 'ball', 'cot', 'doll']
item2 = ['fan', 'goat', 'ink', 'jug']
data = [item1, item2]
export_data = zip_longest(*data, fillvalue = '')
with open('items.csv', 'w', encoding="ISO-8859-1", newline='') as file:
      write = csv.writer(file)
      write.writerow(("item1", "item2"))
      write.writerows(export_data)

In the below screenshot, we can see the data is the column format as the output.

Python write a list to CSV column
Python write a list to CSV column

You may like the following Python tutorials:

In this tutorial, we have learned about the Python write list to CSV, and also we have covered these topics:

  • Python write a list to CSV row
  • Python write a list to CSV header
  • Python write a list to CSV pandas
  • Python write a list to CSV numpy
  • Python write a list to CSV newline
  • Python write a nested list to CSV
  • Python write a list of list to CSV
  • Python append a list to CSV
  • Python write a list to CSV column