CSV File - writer(), writerow() and writerows() function


☞ Create a writer object to write data into csv file – csv.writer( )

☞ Use the pre-defined functions to write data into csv file - <writerobject>.writerow() or <writerobject>.writerows()


csv.writer()

☞ It returns a writer object that converts the user data into a delimited string.

☞ This string can be used to write into CSV files using writerow() or writerows().


writerow() function :

☞To write one row in a csv file.

Example :

import csv

def writing():
    f=open("student.csv","w")
    csv_obj=csv.writer(f)
    csv_obj.writerow(['Name', 'Marks'])
    record=[]
    while True:
        name=input("Enter a name : ")
        marks=int(input("Enter marks : "))
        rec=[name,marks]
        record.append(rec)
        choice=input("Do you want to add more records? [Y/N] : ")
        if choice.lower()=='n':
            break
    for item in record:
        csv_obj.writerow(item)
    f.close()

#start
writing()

Output :


Enter a name : avlokan
Enter marks : 53
Do you want to add more records? [Y/N] : y
Enter a name : alokik
Enter marks : 63
Do you want to add more records? [Y/N] : n
Note :
  1. To remove this space, provide newline argument = ‘ ’ in open( ) i.e.
    f = open("student.csv", "w", newline="")
  2. To use the any other delimiter instead of comma
    csv_obj = csv.writer(f, delimiter = ";")
    using this data will be separated by ;(semi-colon), but if you open this file in excel then also data will be separated by ; .
  3. To get back the data again in the proper format, do the following steps :
    Click on Data tab → From Text/CSV → Import Data file (eg : student.csv) → Open button.

Writerows( ) function

☞ To enter multiple rows at once in a csv file.

Example :

import csv

def writing():
    f=open("student.csv","w", newline='')
    csv_obj=csv.writer(f)
    csv_obj.writerow(['Name', 'Marks'])
    record=[]
    while True:
        name=input("Enter a name : ")
        marks=int(input("Enter marks : "))
        rec=[name,marks]
        record.append(rec)
        choice=input("Do you want to add more records? [Y/N] : ")
        if choice.lower()=='n':
            break
    csv_obj.writerows(record)
    f.close()

#start
writing()

Output :


Enter a name : amit
Enter marks : 45
Do you want to add more records? [Y/N] : y
Enter a name : ankit
Enter marks : 63
Do you want to add more records? [Y/N] : n