Class XII: Python Data File Handling 21

CSV (Comma Separated Values) Files

 

* CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database.

* A CSV file stores tabular data (numbers and text) in plain text.

* Each line of the file is a data record.

* Each record consists of one or more fields, separated by commas.

* The use of the comma as a field separator is the source of the name for this file format.

* CSV files allows to choose a different delimiter character such as ‘\t’, ‘:’ , ‘;’ , ‘|’ . but the default delimiter is ‘,’comma.

* To read and write in CSV files we need to import csv module.

* csv module provides two specific objects -reader and writer to read and write into the file.

* These objects read and write delimited sequence as records in a csv file.

 

Opening a csv file:

A csv file is opened n the same way as any text file is opened.

syntax:

to open the file in write mode
fh=open(“filename”,”w”)

example:
fh=open(“stu.csv”,”w”)

to open the file in write mode
fh=open(“filename”,”r”)

example:
fh=open(“stu.csv”,”r”)

 

Writing in csv file:

Writing into a csv file involves conversion of the user data into the writable delimited form and storing it in the form of csv file.
This is done using following three functions:

sno command and explanation
1.

csv.writer():

returns a writer object which writes data into csv file.

syntax:
writerobject= csv.writer(fileobject)

example : stuwriter=csv.writer(fh)

2

writerobject.writerow()

writes one row of data onto the writer object

example :
stuwriter.writerow(sturec)
#sturec=[23,’Rustom’,79]

 

3.

writerobject.writerows():
writes multiple rows of data onto the writer

example : stuwriter.writerows(sturec)

# sturec=[
[11,’Nishtha’,99],
[12,’Rudy’,’89.0]
]