0% found this document useful (0 votes)
54 views35 pages

Computer science

Uploaded by

Harshit Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views35 pages

Computer science

Uploaded by

Harshit Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

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 csv.writer() function is


contents in a used to create
a writer object
csv file

The writer.writerow() functi


on is then used to write
single rows to the CSV file.
Example
import csv

file=open(‘famous.csv',’w’, newline=“”)

writer = csv.writer(file)

writer.writerow(["SN", "Name", "Contribution"])

writer.writerow([1, "Linus Torvalds", "Linux Kernel"])

writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])

writer.writerow([3, "Guido van Rossum", "Python Programming"])

file.close()
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(‘newinnovators.csv', ‘w’, newline=“”)

writer = csv.writer(file)

writer.writerows(row_list)
file.close()
Q: Write a program to add (append) Employee
records onto a csv
file.
import csv
with open('myfile.csv',mode = 'a') as csvfile:
mywriter = csv.writer(csvfile, delimiter=‘,’,
newline=“”)
ans = 'y' 101Deepak 38000
while ans.lower() == 'y':
121Raunak 58000
eno = int(input("Enter Employee Number:"))
name = input("Enter Employee Name:") 131Reena 80000

salary = int(input("Enter Employee Salary:"))


mywriter.writerow([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('famous.csv', 'r')
reader = csv.reader(file) The csv.reader() 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’]
CSV-Read1.py ['3', 'Guido van Rossum', 'Python Programming']

DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR


Reading a csv file
import csv
with open(‘famous.csv', 'r') as file:
reader = csv.reader(file) The csv.reader() 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']
CSV-Read2.py ['3', ' Guido Van Rossum', ' Python Programming']

DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR


Reading a CSV file

Book.csv 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('famous.csv', 'r') as file:
reader = csv.reader(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('book1.csv','r')
reader = csv.reader(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('book1.csv','r')
reader = csv.reader(file, skipinitialspace=True)
for row in reader:
c=c+1
print(row)
CSV-Read3.py
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("famous.csv", 'r')
count=0
reader=csv.reader(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)
f.close()

DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR


Q Write user-defined functions to perform read and write operation
onto a student.csv file having fields as
roll number, name, stream and marks.

def writecsv(): def menu():


fobj=open("student.csv", 'a') while True:
rno=int(input("Enter print("1. Read data")
rollno")) print("2. Write data")
nm=input("Enter name") print("3.exit")
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():
= csv.writer(fobj) writecsv()
f=open("student.csv",
csv_w.writerow(row) 'r') else:
data = csv.reader(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 student.csv 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 employee.csv 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 Emp.csv containing
Empno(Employee number, Wrate(hourly wage rate), NOH(No of hours
worked/week) fields. Write a UDF to read each record from Emp.csv
and compute weekly wage rate as Wrate*NOH and write into
EmpPayment.csv and display Empno, Wrate, NOH, Wrate*NOH
import csv
def writecsv(): def compute():
fobj=open("Emp.csv", 'a') f1=open("Emp.csv",'r')
Empno=input("Enter Empno") f2=open("EmpPayment2.csv",'a')
Wrate=int(input("Enter hourly wage data = csv.reader(f1)
rate")) wr=csv.writer(f2)
Noh = int(input("Enter No. of hours
worked")) wr.writerow(['Empno','Wrate','NOH','Wrat
row = [Empno,Wrate,Noh] e*Noh'])
csv_w = csv.writer(fobj) c=1
csv_w.writerow(row) for row in data:
def readf(): if c%2!=0:
fobj.close()
f=open("EmpPayment2.csv",'r') cal=int(row[1])*int(row[2])
data = csv.reader(f)
for row in data: writecsv() wr.writerow([row[0],row[1],row[2],cal ])
print(row) compute( CSV_WageRate.py
c+=1
f.close() ) f1.close()
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
readf() f2.close()
Question: Read the book1.csv 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('book1.csv','r')
reader = csv.reader(file, skipinitialspace=True)
l=[]
c=0
for i in reader:
if(c>0):
l.append(i)
c=c+1
print(l)
bubblesort(l)
print(l)
DEEPSHIKHA SETHI -----XII COMPUTER SCIENCE -----AIS MAYUR VIHAR
Question: Read the book1.csv file and sort
the records in descending order of marks
import csv
def function(k):
return int(k[2])
file=open('book1.csv','r')
reader = csv.reader(file, skipinitialspace=True)
l=[]
c=0
for i in reader:
if(c>0):
l.append(i)
c=c+1
l.sort(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 “user.csv” 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(' user.csv','________’) # LineaddCsvFile(“Arjun”,”123@456”)
2
addCsvFile(“Arunima”,”aru@nima”)
newFileWriter = csv.writer(f)
addCsvFile(“Frieda”,”myname@FRD
newFileWriter.writerow([UserName,PassWord])”) readCsvFile() #Line 5
f.close()
def readCsvFile():
with open(' user.csv','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 “user.csv” 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(' user.csv’,’ ’a’) addCsvFile(“Arjun”,”123@456”)
# Line 2
addCsvFile(“Arunima”,”aru@nima”)
newFileWriter = csv.writer(f)
addCsvFile(“Frieda”,”myname@FRD
newFileWriter.writerow([UserName,PassWord])”) readCsvFile() #Line 5
f.close()
def readCsvFile():
with open(' user.csv','r') as newFile:
newFileReader = csv.reader(newFile) #Line 3
for row in newFileReader:
print (row[0],row[1])
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar

newFile.close() #Line 4
CSV 1*5 marks
The program needs to be be made to read the
file volume.csv 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(‘ volume.csv','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 volume.csv 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(‘ volume.csv','r') as newFile: #Line 1

obj = csv.reader(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 'Student.csv' (content
shown below). Help him in completing the
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
code which creates the desired CSV File.
data.append(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
data.append(rec)
stuwriter. _____ (data)
Deepshikha Sethi ----XII Computer Science ----AIS Mayur Vihar #Statement-5
fh.close()
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 placement.csv conducted and each
placement.csv 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

You might also like