0% found this document useful (0 votes)
2 views6 pages

4.3 Notes of CSV file

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

Notes of CSV File

CSV File stands for Comma Separated Values File.

CSV files are delimited files that store tabular data where comma delimits every value.

The default delimiter of CSV files is the comma (,) but we can use different delimiter character other than
comma.

Advantages of CSV files


 Easier to create

 It preferred export and import format for databases and spread sheets.

 It is capable of storing large amounts of data

Python CSV Module


The CSV module provides function to read and write tabular data in CSV format.

It provides two special objects writer and reader to write and read in CSV files.

Q. How to import csv module?

Ans. import csv

Open CSV File


Opening of CSV file is same as we open any text file but make sure for two things:

 The file extension is .csv

 Use of modes text file

We can open CSV file by two ways

1. By using open function

2. By using with statement

1. By using open function


FileObject = open('FileName.csv','mode', newline='character')

Modes are r, w, a, r+, w+, a+.

Use of newline: It is an additional argument but it is optional. It specifies that how would python
handle newline characters while working with CSV files.

1
Working on EOL (End of Line) character is depend on operating system because different operating system
uses different default EOL character.

Windows uses '\r\n' as default EOL character.

Ex: f = open('sunshine.csv','w',newline='')

2. By using with statement


with open('FileName.csv','mode',newline='character') as FileObject:

Statement

Ex: with open('SunShine.csv','r',newline='\r\n') as f:

statement

Close CSV File


FileObject.close()

Ex: f.close()

Writing in CSV File


Writing into CSV file involves the conversion of the user data into the writable delimited form and then
storing it in the form of CSV.

Python CSV module provides three functions first function to create writer object and other two functions
for writing data into the file.

1. writer(): It returns a writer object which writes data into CSV file.

Syntax: WriterObject = csv.writer(FileObject, delimiter='DelimiterCharacter')

Ex: wo = csv.writer(f)

2. writerow(): It writes one row of data onto the writer object.

Syntax: WriterObject.writerow(Data To Be Write)

Ex: wo.writerow([value1,value2,...])

3. writerows(): It writes multiple rows of data onto the writer object.

Note: If we have all the data available and data is not much lengthy then it is possible to write all data in
one go by using writerows() function. But we need to create a nested sequence of data then we can write.

Syntax: WriterObject.writerows(Data To Be Write)

Ex: wo.writerow([ [value1,value2,...] , [value1,value2,...] ] )

2
Note: It is important to convert the received data into the form appropriate for the CSV file. This task is
performed by writer object.

Note: We can use list data type or tuple data type to write data in the CSV file.

WAP to create a csv file data.csv in which write the record of 4 students like rno,name,marks.

import csv

f=open('data.csv','a')

wo=csv.writer(f)

wo.writerow(['Roll No','Name','Marks'])

for i in range(4):

r=int(input('Enter your roll no :'))

n=input('Enter name of Student :')

m=float(input('Enter marks :'))

wo.writerow([r,n,m])

f.close()

Appending Data in CSV File


We can add more record in CSV file by using mode 'a'.

WAP to append record of 2 more student in the file data.csv.

import csv

f=open('data.csv','a')

wo=csv.writer(f)

for i in range(2):

r=int(input('Enter your roll no :'))

n=input('Enter name of Student :')

3
m=float(input('Enter marks :'))

wo.writerow([r,n,m])

f.close()

Reading From CSV File


Reading from a csv file involves loading of a csv file data, Parsing, loading it in python iterable and then
reading from this iterable.

Note: Parsing means to remove the delimiter.

Python CSV module provides one function to create reader object.

reader(): It returns a reader object which loads data from CSV file into an iterable after parsing
delimited data.

Syntax: ReaderObject = csv.reader(FileObject,delimiter='Delimiter Character')

Ex: ro = csv.reader(f, delimiter = ',')

Note: The csv.reader() object does the opposite of csv.writer() object. The csv.reader() object loads data
from the CSV file, parse it and returns the data in form of a python iterable where we can fetch one by one
row by using for loop.

Q. How top fetch data row by row?

Ans. Syntax: for variable in ReaderObject:

print(variable)

Ex: for L in ro:

print(L)

Note: All data present in csv file is consider as string data type. It means file contains list of strings.

WAP to read and display record of all the students present in the file data.csv.

import csv

4
f=open('data.csv','r')

ro=csv.reader(f)

for rec in ro:

print(rec)

f.close()

Output:

['Roll No', 'Name', 'Marks']

[]

['1', 'Abhay', '27.9']

[]

['2', 'Amit', '39.75']

[]

['3', 'karan', '12.0']

[]

['4', 'Nitin', '39.42']

[]

['5', 'Rahul', '21.0']

[]

['6', 'Aryan', '30.02']

[]

Note: We never entered empty rows. Then where have these empty rows come from? Because we did
not specify the newline argument in the file open() function while creating this CSV file. EOL translation
took place, which result in the blank rows after every record while reading.

Note: Every data record line was appended with EOL character '\r\n' on the windows.

This situation is handled by two ways:

(i) Method1: Write onto CSV file with newline=''(Without space) argument in open() function.

Ex: f = open('FileName.csv','w',newline='')

5
(ii) Method2: To read data from CSV file, which is created with EOL translation. Open it with
newline='\r\n' argument.

Ex: f = open('FileName.csv','r',newline='\r\n')

WAP to read and display record of all the students present in the file data.csv.

import csv

f=open('data.csv','r',newline='\r\n')

ro=csv.reader(f)

for rec in ro:

print(rec)

f.close()

Output:

['Roll No', 'Name', 'Marks']

['1', 'Abhay', '27.9']

['2', 'Amit', '39.75']

['3', 'karan', '12.0']

['4', 'Nitin', '39.42']

['5', 'Rahul', '21.0']

['6', 'Aryan', '30.02']

You might also like