Writing data from a Python List to CSV row-wise

Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format.  A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class.

Example 1:
Creating a CSV file and writing data row-wise into it using writer class.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing library
import csv
  
# data to be written row-wise in csv fil
data = [['Geeks'], [4], ['geeks !']]
  
# opening the csv file in 'w+' mode
file = open('g4g.csv', 'w+', newline ='')
  
# writing the data into the file
with file:    
    write = csv.writer(file)
    write.writerows(data)

chevron_right


Output:

Example 2:
Writing data row-wise into an existing CSV file using DictWriter class.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing library
import csv
  
# opening the csv file in 'w' mode
file = open('g4g.csv', 'w', newline ='')
  
with file:
    # identifying header  
    header = ['Organization', 'Established', 'CEO']
    writer = csv.DictWriter(file, fieldnames = header)
      
    # writing data row-wise into the csv file
    writer.writeheader()
    writer.writerow({'Organization' : 'Google'
                     'Established': '1998'
                     'CEO': 'Sundar Pichai'})
    writer.writerow({'Organization' : 'Microsoft'
                     'Established': '1975',
                     'CEO': 'Satya Nadella'})
    writer.writerow({'Organization' : 'Nokia',
                     'Established': '1865',
                     'CEO': 'Rajeev Suri'})

chevron_right


Output:

Example 3:
Appending data row-wise into an existing CSV file using writer class.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing library
import csv
  
# data to be written row-wise in csv fil
data = [['Geeks for Geeks', '2008', 'Sandeep Jain'],
        ['HackerRank', '2009', 'Vivek Ravisankar']]
  
# opening the csv file in 'a+' mode
file = open('g4g.csv', 'a+', newline ='')
  
# writing the data into the file
with file:    
    write = csv.writer(file)
    write.writerows(data)

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.