CSV File Handling Doc
CSV File Handling Doc
csv Module: The CSV module is one of the modules in Python that provides classes
for reading and writing tabular information in CSV file format.
Note: The ‘with’ keyword is used along with the open() method as it simplifies
exception handling and automatically closes the CSV file.
Example: This code reads and prints the contents of a CSV file
named ‘Giants.csv’ using the csv module in Python. It opens the file in read mode,
reads the lines, and prints them one by one using a for loop. The csv.reader() function
is used to read the CSV file, and the data from each row is printed to the console.
import csv
# opening the CSV file
File= open('Giants.csv', mode ='r')
Syntax:
csv.writer(csvfile)
writerow(): This method writes a single row at a time. Field row can be written using
this method.
Syntax:
writerow()
writerows(): This method is used to write multiple rows at a time. This can be used
to write rows list.
Syntax:
writerows(rows)
# writing to CSV
import csv
filename = "university_records.csv"
csvwriter = csv.writer(csvfile)
csvwriter.writerows([ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2',
'9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']])