Python
csv files
CL ASS XII COMPUTER
SCIENCE
Learning Objectives
Introduction of CSV Files
Advantages of CSV files
Explanation on writer and reader objects of csv files
Programs on writerow() and writerows() methods
Use of reader object
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
A CSV file (Comma Separated Values
file) is a type of plain text file that
uses specific structuring to arrange
tabular data.
Because it’s a plain text file, it can
contain only actual text data—in other What is a
words, printable ASCII or Unicode
characters. CSV File
CSV files use a comma to separate
each specific data value.
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
CSV files can be opened or edited by text editors like
notepad.
CSV follows a fairly flat, simple schema
Any programming language to parse CSV data is
trivial
Advantage
CSV is safe and can clearly differentiate between the
s of using
numeric values and text.
CSV Files
Importing CSV files can be much faster, and it also
consumes less memory
CSV Files are fast
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Parsing CSV files with Python
built in library
Designed to work out
The csv library
of the box with Excel-
provides
generated CSV files,
functionality to both
it is easily adapted to
read from and write
work with a variety of
to CSV files.
CSV formats.
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Open the csv file in writing
mode
using open() function.
To write the the [Link]() function is
contents in a used to create
a writer object
csv file
The [Link]() functi
on is then used to write
single rows to the CSV file.
Example
import csv
file=open(‘[Link]',’w’, newline=“”)
writer = [Link](file)
[Link](["SN", "Name", "Contribution"])
[Link]([1, "Linus Torvalds", "Linux Kernel"])
[Link]([2, "Tim Berners-Lee", "World Wide Web"])
[Link]([3, "Guido van Rossum", "Python Programming"])
[Link]()
Writing multiple rows
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python
Programming"]]
file=open(‘[Link]', ‘w’, newline=“”)
writer = [Link](file)
[Link](row_list)
[Link]()
Q: Write a program to add (append) Employee
records onto a csv
file.
import csv
with open('[Link]',mode = 'a') as csvfile:
mywriter = [Link](csvfile, delimiter=‘,’,
newline=“”)
ans = 'y' 101Deepak 38000
while [Link]() == 'y':
121Raunak 58000
eno = int(input("Enter Employee Number:"))
name = input("Enter Employee Name:") 131Reena 80000
salary = int(input("Enter Employee Salary:"))
[Link]([eno,name,salary])
print("## Data Saved… ##")
ans = input("Add More?")
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
The CSV file is opened as a text
file with Python’s built-
in open() function, which
returns a file object.
Reading from a CSV file is
done using the iterable
Reading a
reader object. csv file
The reader object is then
iterated using a for loop to
print the contents of each
row
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Reading a csv file
import csv
file=open('[Link]', 'r')
reader = [Link](file) The [Link]() is used to read the file, which returns
an iterable reader object.
print(reader)
for row in reader: Output:
print(row) <_csv.reader object at 0x10e0763c8>
['SN', 'Name', 'Contribution’]
['1', 'Linus Torvalds', 'Linux Kernel’]
['2', 'Tim Berners-Lee', 'World Wide Web’]
[Link] ['3', 'Guido van Rossum', 'Python Programming']
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Reading a csv file
import csv
with open(‘[Link]', 'r') as file:
reader = [Link](file) The [Link]() is used to read the file,
which returns an iterable reader object.
for row in reader:
print(row) Output:
['Sno', ' Name', ' Contribution']
['1', ' Linus Torvalds', ' Linux Kernel']
['2', ' Tim Berners-Lee', ' World Wide web']
[Link] ['3', ' Guido Van Rossum', ' Python Programming']
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Reading a CSV file
[Link] created in The same file when
excel opened in notepad
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
By default, a comma is
used as a delimiter in a
CSV file.
CSV files
with However, some CSV files
Custom can use delimiters other
Delimiters than a comma.
Few popular ones
are | and \t
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
CSV files with Custom Delimiters
Example 2: Read CSV file Having Tab Delimiter
import csv
with open('[Link]', 'r') as file:
reader = [Link](file, delimiter = '\t')
for row in reader:
print(row)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
CSV files with initial spaces
Some CSV files can have a space character after a delimiter.
To remove these initial spaces, we need to pass an additional parameter
called skipinitialspace
import csv
csvfile=open('[Link]','r')
reader = [Link](csvfile,
skipinitialspace=True)
for row in reader:
print(row)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Python
csv files
CL ASS XII COMPUTER SCIENCE
22 N D JULY 2021
Learning Objectives
Recap of writer and reader object of CSV file
Explanation of line_num parameter
Programs on reader()
Discussion of CBSE previous year questions
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Question: To find the number of
records in a csv file
import csv
c=0
file=open('[Link]','r')
reader = [Link](file, skipinitialspace=True)
for row in reader:
c=c+1
print(row)
[Link]
print(c)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Question: To find the number of records in a csv file with line_num
line_num is nothing but a counter which returns the
number of rows which have been iterated.
CSV-Line_num.py
The No. of lines are = 10
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Question: To find the number of records in a csv file with line_num
import csv
f=open("[Link]", 'r')
count=0
reader=[Link](f, skipinitialspace=True)
for row in reader:
if reader.line_num==1:
continue
else:
print(row)
print("The number of rows are =", reader.line_num)
[Link]()
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Q Write user-defined functions to perform read and write operation
onto a [Link] file having fields as
roll number, name, stream and marks.
def writecsv(): def menu():
fobj=open("[Link]", 'a') while True:
rno=int(input("Enter print("1. Read data")
rollno")) print("2. Write data")
nm=input("Enter name") print("[Link]")
stream = input("Enter a = int(input("Enter your
stream") choice"))
mks=int(input("Enter if a == 1:
marks")) readcsv()
row = [rno,nm,stream,mks] elif a == 2:
defcsv_w
readcsv():
= [Link](fobj) writecsv()
f=open("[Link]",
csv_w.writerow(row) 'r') else:
data = [Link](f) break
for row in data: menu()
print(row) CSV_student.py
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Q:UDF to perform read operation onto a [Link] file
having fields as :
roll number, name, stream, marks. Display those records
whose stream is Humanities
Rno Name Stream Marks
1 Akash Science 95 CSV_readStream.py
2 Deepak Commerce 90
3 Aman Humanities 80
4 Fatima Science 89
5 Gauri Humanities 93
Output:
['3', 'Aman', 'Humanities', '80']
['5', 'Gauri', 'Humanities', '93']
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Q:UDF to perform read operation onto a [Link] file
having fields as :
Ecode,Ename,Salaries
Display those records whose salaries between 25000 to
30000.
CSV_readSalary.py
Ecode Ename Salary
A12 Tarun Kumar 28000
A13 Deepak 35000
A14 Sheena 32000
A15 Deepa 45000
A16 Hemant 29000
Output:
['A12', 'Tarun Kumar', '28000']
['A15', 'Deepa', '25000']
['A16', 'Hemant', '29000']
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Q Write user-defined functions to create a csv file [Link] containing
Empno(Employee number, Wrate(hourly wage rate), NOH(No of hours
worked/week) fields. Write a UDF to read each record from [Link]
and compute weekly wage rate as Wrate*NOH and write into
[Link] and display Empno, Wrate, NOH, Wrate*NOH
import csv
def writecsv(): def compute():
fobj=open("[Link]", 'a') f1=open("[Link]",'r')
Empno=input("Enter Empno") f2=open("[Link]",'a')
Wrate=int(input("Enter hourly wage data = [Link](f1)
rate")) wr=[Link](f2)
Noh = int(input("Enter No. of hours
worked")) [Link](['Empno','Wrate','NOH','Wrat
row = [Empno,Wrate,Noh] e*Noh'])
csv_w = [Link](fobj) c=1
csv_w.writerow(row) for row in data:
def readf(): if c%2!=0:
[Link]()
f=open("[Link]",'r') cal=int(row[1])*int(row[2])
data = [Link](f)
for row in data: writecsv() [Link]([row[0],row[1],row[2],cal ])
print(row) compute( CSV_WageRate.py
c+=1
[Link]() ) [Link]()
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
readf() [Link]()
Question: Read the [Link] file and sort
the records in descending order of marks
import csv
def bubblesort(l):
for i in range(len(l)):
for j in range(len(l)-i-1):
if(int(l[j][2])<int(l[j+1][2])):
l[j],l[j+1]=l[j+1],l[j]
file=open('[Link]','r')
reader = [Link](file, skipinitialspace=True)
l=[]
c=0
for i in reader:
if(c>0):
[Link](i)
c=c+1
print(l)
bubblesort(l)
print(l)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Question: Read the [Link] file and sort
the records in descending order of marks
import csv
def function(k):
return int(k[2])
file=open('[Link]','r')
reader = [Link](file, skipinitialspace=True)
l=[]
c=0
for i in reader:
if(c>0):
[Link](i)
c=c+1
[Link](key=function)
print(l)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Recap
1. Fill in the blanks.
(a) ..................... format is a text format, accessible to all applications across several
platforms.
(b) ..................... object contains the number of the current line in a CSV file.
(c) Every record in a CSV file is stored in reader object in the form of a list using
……………….. method?
2. State whether the following statements are True or False.
(a) CSV module can handle CSV files correctly regardless of the operating system on
which the files were created.
(b) CSV module gets automatically imported into your program for reading a CSV file.
(c) Every record in a CSV file is stored in reader object in the form of a list.
(d) Comma is the default delimiter for a CSV file.
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
CBSE 2020 1*5 marks CSV
Ranjan Kumar of class 12 is writing a program to create a CSV file “[Link]” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to
successfully execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): CSV file
f=open(' [Link]','________’) # LineaddCsvFile(“Arjun”,”123@456”)
2
addCsvFile(“Arunima”,”aru@nima”)
newFileWriter = [Link](f)
addCsvFile(“Frieda”,”myname@FRD
[Link]([UserName,PassWord])”) readCsvFile() #Line 5
[Link]()
def readCsvFile():
with open(' [Link]','r') as newFile:
newFileReader = csv._________(newFile) #Line 3
for row in newFileReader:
print (row[0],row[1]) Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar
newFile.______________ #Line 4
CBSE 2020 1*5 marks CSV
Ranjan Kumar of class 12 is writing a program to create a CSV file “[Link]” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to
successfully execute the given task.
import csv # Line 1
def addCsvFile(UserName,PassWord): CSV file
f=open(' [Link]’,’ ’a’) addCsvFile(“Arjun”,”123@456”)
# Line 2
addCsvFile(“Arunima”,”aru@nima”)
newFileWriter = [Link](f)
addCsvFile(“Frieda”,”myname@FRD
[Link]([UserName,PassWord])”) readCsvFile() #Line 5
[Link]()
def readCsvFile():
with open(' [Link]','r') as newFile:
newFileReader = [Link](newFile) #Line 3
for row in newFileReader:
print (row[0],row[1])
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar
[Link]() #Line 4
CSV 1*5 marks
The program needs to be be made to read the
file [Link] and sum of open,high,low and
close needs to be done for each row and total
rows need to be counted
def readRecord():
cnt=0
with open(‘ [Link]','r') as newFile: #Line 1
obj = csv._________(newFile) #Line 2
for ______________________: # Line 3
sum=_______________ #Line 4
cnt=cnt+_________________ #Line 5
print(”Sum of data”,sum)
print(“Total number of records”,cnt)
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar
CSV 1*5 marks
The program needs to be be made to read the
file [Link] and sum of open,high,low and
close needs to be done for each row and total
rows need to be counted
def readRecord():
cnt=0
with open(‘ [Link]','r') as newFile: #Line 1
obj = [Link](newFile) #Line 2
for row in obj: # Line 3
sum=float(row[1])+float(row[2])+float(row[3])
+int(row[4]) #Line 4
cnt=cnt+1 #Line 5
print(”Sum of data”,sum)
print(“Total number of records”,cnt)
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar
import_____ #Statement-1 Rohit, a student of class 12th, is learning
fh = open(_____, _____, newline='') #Statement-2 CSV File Module in Python. During
examination, he has been assigned an
stuwriter = csv._____ #Statement-3 incomplete python code (shown below) to
data = [ ] create a CSV File '[Link]' (content
shown below). Help him in completing the
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
code which creates the desired CSV File.
[Link](header) 1,AKSHAY,XII,A
for i in range(5): 2,ABHISHEK,XII,A
roll_no = int(input("Enter Roll Number : ")) 3,ARVIND,XII,A
name = input("Enter Name : ") 4,RAVI,XII,A
Class = input("Enter Class : ") 5,ASHISH,XII,A
section = input("Enter Section : ")
rec = [_____] #Statement-4
[Link](rec)
stuwriter. _____ (data)
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar #Statement-5
[Link]()
Practical Question 6
Sun Microsystems
when held The marks are from 5
a) Write a function to
recruitment test. The different tests
append data in
file [Link] conducted and each
[Link] file
containing the below col is out of 5 marks
format of data
c) Write User Defined
d) Write the UDF to
b) Read the above Function to find total
find the top n Names
file and print the no of people who
on basis of total
data came for the
Marks
placement test
Practical list Q3
A file containing data about a collection of students has the following format.
Rajat Sen 12345 1 CSEE
Jagat Narain 13467 3 CSEE
Anu Sharma 11756 2 Biology
Sumita Trikha 23451 4 Biology
Sumder Kumra 11234 3 MME
Kanti Bhushan 23211 3 CSEE
Each line contains a first name, a second name, a registration number, no of years and a
department separated by tabs.
1. Write a Python program that will copy the contents of the file into a list of tuples
2. Display full details of the student sorted by registration number
· The names of all students with no of year less than 3
· The number of people in each department