CSV Files
Marks CSV Files Total
(Question) Marks
Section A 1 - -
Section B 2 - -
Section C 3 - -
Section D 4 1 4
Section E 5 1 5
Total 09
● CSV is a simple file format used to store tabular data, such as a spread sheet or database.
● CSV stands for "comma-separated values“.
● Files in the CSV format can be imported to and exported from programs that store data in
tables, such as Microsoft Excel or Open Office Calc.
Important Steps:
1. First of all we have to import csv module for file operation.
2. For writing ,we open file in ‘w’ writing or ‘a’ append mode using open() method
f=open(‘filename.csv’,’w’,newline=’’)
By setting newline='', you're telling Python not to modify the newline characters at all. This is commonly used when
working with the csv module to ensure that the csv.writer handles the newline characters correctly (i.e., without
adding extra blank lines between rows).
3. For Writing
Creating a writer object, associated with the file f. The writer object allows you to write rows
of data into the file in CSV format. Through csv.writer() method ,we create it.
w_obj=csv.writer(f)
For Reading
Creating a reader object, associated with the file f we use csv.reader() method. It Creates a
CSV reader object that can iterate over the rows of the file f.
r_obj=csv.reader(f)
4. Perform writing operation (read data from user and write on to csv file)
writerow() used for writing single row
writerows()used for writing multiple rows
Perform reading operation (read data from csv file and display using python)
5. Close the file using close() method
f.close()
Examples: Writing to csv file
import csv import csv
f = open("data.csv", 'w') fields = ['Name', 'Class', 'Subject']
wr = csv.writer(f) rows = [["Amit", 'XII', 'CS'], ['Sumit', 'X', 'ΙΡ'], ['Ashu', 'XI', 'CS']]
wr.writerow(['Name', 'Class']) f = open("data.csv", 'w', newline = ' ')
wr.writerow (['Amit', 'XII']) wr = csv.writer(f)
f.close() wr.writerow (fields) # adding 1 row
wr.writerows(rows) # adding 3 rows
f.close()
Examples: Reading from csv file
import csv import csv
f = open("data.csv", 'r') f = open("data.csv", 'r')
row = csv.reader(f) row = csv.reader(f)
for i in row: for i in row:
print(i) print(i[0], i[2])
The above code is reading first and third column from "data.csv" file
Sample Programs CSV Files (09 Marks)
A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following
data:
* Name of a country
* Population of the country
* Sample Size (Number of persons who participated in the survey in that country)
* Happy (Number of persons who accepted that they were Happy)
For example, a sample record of the file may be: Signiland, 5673000, 5000, 3426
Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file and display all (II) Count the number of records in the file.
those records for which the population is more
than 5000000. def Count_records():
import csv f=open("happiness.csv",'r')
def show(): r =csv.reader(f)
f=open("happiness.csv",'r') next(r, None) #To skip the Header row
r=csv.reader(f) count=0
next(r, None) #To skip the Header row for i in r:
for i in r: count+=1
if int(i[1])>5000000: print(count)
print(i) f.close()
f.close()
Surya is a manager working in a recruitment agency. He needs to manage the records of various
candidates. For this he wants the following information of each candidate to be stored:
Candidate_ID – integer
Candidate_Name – string
Designation – string
Experience – float
You, as a programmer of the company, have been assigned to do this job for Surya. Suggest:
(I) What type of file (text file, csv file, or binary file) will you use to store this data? Give one valid
reason to support your answer.
(I) CSV File: A CSV file allows for easy maintenance of data, as it can be opened and manipulated with
any spreadsheet application also.
(II) Write a function to input the data of a (III) Write a function to read the data from the
candidate and append it in the file that you file that you suggested in part (I) of this question
suggested in part (I) of this question. and display the data of all those candidates
whose experience is more than 10.
Import csv
def append(): Import csv
f=open("Candidates.csv",'a',newline='') def display():
C_id=input("Enter Candidate ID: ") f=open("Candidates.csv")
C_nm=input("Enter Candidate name: ") r=csv.reader(f)
C_dg=input("Enter Designation: ") for rec in r:
C_ex=input("Enter Experience: ") if float(rec[3])>10:
rec=[C_id,C_nm,C_dg,C_ex] print(rec)
w=csv.writer(f) f.close()
w.writerow(rec)
f.close()
Sample Programs CSV Files (09 Marks)
A CSV file "HealthData.csv" contains the data of a health survey. Each record of the file contains the
following data:
● Name of a country
● Life Expectancy (average number of years a person is expected to live)
● GDP per capita (Gross Domestic Product per person)
● Percentage of population with access to healthcare
For example, a sample record of the file may be: ['Wonderland', 82.5, 40000, 95].
Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file and display all (II) Count the number of records in the file.
those records for which the life expectancy is
greater than 75. import csv
def count_records( ):
import csv f=open(‘HealthData.csv’, ‘r'):
def health_data(): r = csv.reader(f)
f=open(‘HealthData.csv’, ‘r'): next(r, None) # #To skip the Header row
r = csv.reader(f) count=0
next(r, None) # #To skip the Header row for row in r:
for row in r: count+=1
if float(row[1])>75 : print(‘Total records are:’,count)
print(row) f.close()
f.close()
A csv file " record.csv " contains the data . Each record consists of a list with field elements as
Empid, Name & Sal to store employee id, employee name and employee salary respectively.
Write user defined functions s in Python that defines the following:
(i) ADD() – To accept and add data of an (ii) COUNTR() – To count the number of records
employee to a CSV file ‘record.csv’. present in the CSV file named ‘record.csv’ whose
salary is more than 100000.
import csv
def ADD(): def COUNTR():
f=open(" record.csv",'w',newline=’’) f=open(”record.csv",'r')
w=csv.writer(f) r=csv.reader(f)
w.writerow(['Empid','Name','Salary']) count=0
while True: for i in r:
empid=int(input("Enter your employee id:")) if(i[2]>100000):
name=input("Enter your name:") count+=1
sal=int(input("Enter your salary:")) print("No of records in the file:",count)
w.writerow([empid,name,sal]) f.close()
print("Do you want to enter more records:")
ch=input()
if(ch=='n'):
break
f.close()
Sample Programs CSV Files (09 Marks)
Abhishek is making a software on “Countries & their Capitals” in which various records are to be
stored/retrieved in CAPITAL.CSV data file. It consists of some records. As a programmer, you have to
help him to successfully execute the program.
(A) Write a function in Python named import csv
AddNewRec(Country,Capital) to append def AddNewRec(Country,Capital):
following records in the file “CAPITAL.CSV”. f=open("CAPITAL.CSV",'a', newline=’’)
[“FRANCE”,”PARIS”] w=csv.writer(f)
[“SRILANKA”,”COLOMBO”] w.writerow([“FRANCE”,”PARIS”])
w.writerow([“SRILANKA”,”COLOMBO”])
f.close()
(B) Write a function in Python named def ShowRec():
ShowRec() that will show all the contents of f=open("CAPITAL.CSV","r")
CAPITAL.CSV r=csv.reader(f)
for rec in r:
print(rec[0],rec[1])
A CSV file "WeatherData.csv" contains the data collected from various weather stations. Each record
in the file includes the following data:
• Name of the city
• Average temperature (in Celsius)
• Humidity percentage
• Rainfall (in millimeters)
For example, a sample record in the file might look like: ['Rainford', 32, 75, 120]
Write the following Python functions to perform the specified operations on this file:
(i) Read all the data from the file in the form of a (ii) Calculate and display the average rainfall
list and display all those records where the across all records in the file.
average temperature is above 30 degrees
Celsius. Import csv
def calculate():
import csv f=open(‘WeatherData.csv’,'r')
def display_hot_cities(): r= csv.reader(f)
f=open(‘WeatherData.csv’,'r') next(r, None)
r= csv.reader(f) total_rainfall = 0
next(r, None) count = 0
for data in r: for data in rr:
if float(data[1]) > 30: total_rainfall += float(row[3])
print(row) count += 1
f.close() avg_rainfall = total_rainfall/count
print("Avg Rainfall:”,avg_rainfall )
f.close()
Sample Programs CSV Files (09 Marks)
Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a
csv file named Result.csv, to store the results of students in different sports events. The structure of
Result.csv is : [St_Id, St_Name, St_Game, St_Result]
Where
St_Id is Student ID (integer)
St_Name is Student Name (string)
St_Game is name of game in which student is participating(string)
St_Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions: As a Python expert, help him complete the task.
Accept() – to accept a record from the user and wonCount() – to count the number of students
add it to the file Result.csv. The column headings who have won any event.
should also be added on top of the csv file.
import csv import csv
def Accept(): def wonCount():
f=open(‘Result.csv’,’r’): f=open(‘Result.csv’,’r’):
r=csv.reader(f) r=csv.reader(f)
St_Id=int(input(‘Student ID’)) next(r, None)
St_Name=input(‘Student Name’) for data in r:
St-Game=input(‘Student Game’) if (data[3]) ==’Won’:
St_Result=input(‘Student Result’) print(row)
Title=[‘Student ID’,’Student Name’,’Student f.close()
Game’,’Student Result’]
Data=[St_Id,St_Name,St_Game,St-Result]
r.writerow(Title)
r.writerow(Data)
f.close()
A csv file "furdata.csv" contains the details of furniture. Each record of the file contains the following
data:
● Furniture id
● Name of the furniture
● Price of furniture
For example, a sample record of the file may be: [‘T2340’, ‘Table’, 25000]
Write the following Python functions to perform the specified operations on this file:
a. add() – To accept and add data of a furniture b. search() – To display the records of the
to a CSV file furdata.csv. Each record consists of furniture whose price is more than 10000.
a list with field elements as fid, fname, fprice to # Function to search and display furniture with
store furniture id, furniture name and furniture price more than 10000
price respectively def search():
import csv with open('furdata.csv', 'r') as file:
# Function to add furniture data to the CSV file reader = csv.reader(file)
def add(): print("\nFurniture with price greater than
with open('furdata.csv', 'a', newline='') as file: 10000:")
writer = csv.writer(file) found = False
fid = input("Enter Furniture ID: ") for row in reader:
fname = input("Enter Furniture Name: ") if float(row[2]) > 10000:
fprice = float(input("Enter Furniture Price: ")) print(f"Furniture ID: {row[0]}, Name: {row[1]},
record = [fid, fname, fprice] Price: {row[2]}")
writer.writerow(record) found = True
print("Furniture record added successfully!") if not found:
print("No furniture found with price greater than 10000.")
Sample Programs CSV Files (09 Marks)
A csv file "candidates.csv" contains the data collected from an online application form for selection of
candidates for different posts, with the following data
Candidate Name
Qualification
Percent_XII
Percent_Qualification
E.g. [‘Smith Jones’, ‘M Tech’, 80, 76]
Write the following Python functions to perform the specified operations on this file:
READ() function which can read all the data from IDENTIFY() function which can find and print the
the file and display only records with Percent_XII number of such records which are having
more than 75 Percent_XII not more than 75
import csv def IDENTIFY():
def READ(): count=0
with open(“candidates.csv”, “r”) as csv_file: with open(“candidates.csv”, “r”) as csv_file:
reading=csv.reader(csv_file) reading=csv.reader(csv_file)
for x in reading: for x in reading:
if x[2]>75 : if x[2]<=75 :
print(x) count=count+1
print(“number of records less then 75% “
,count)