☞ 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()
☞ 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().
☞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
☞ 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