CSV FILE HANDLING
Reading Data from a CSV File
import csv
def read_csv_file():
# Open the file in read mode
with open('[Link]', mode='r', newline='') as file:
# Create a CSV reader object
csv_reader = [Link](file)
# Loop through each row in the file and print it
for row in csv_reader:
print(row) # Each row is a list of strings
read_csv_file()
Writing Data to a CSV File (using writerow )
import csv
def write_csv_file():
# Open the file in write mode with newline=''
with open('[Link]', mode='w', newline='') as file:
# Create a CSV writer object
csv_writer = [Link](file)
# Write the header row
csv_writer.writerow(['RollNo', 'Name', 'Marks'])
# Write data rows
csv_writer.writerow([1, 'Rahul', 90])
csv_writer.writerow([2, 'Ajay', 91])
print("Data written to [Link]")
write_csv_file()
Appending Records to a CSV File (using writerows in a loop)
def append_records():
# Open the file in append mode
with open('[Link]', mode='a', newline='') as file:
csv_writer = [Link](file)
while True:
st_id = int(input("Enter Student ID: "))
st_name = input("Enter Student name: ")
st_score = int(input("Enter score: "))
# Data for a single row
record = [st_id, st_name, st_score]
# Write the new record
csv_writer.writerow(record)
choice = input("Want to insert more records? (y/n): ")
if [Link]() != 'y':
break
print("Records added.")
append_records()
Counting Records in a CSV File
import csv
def count_records():
count = 0
with open('[Link]', mode='r', newline='') as file:
csv_reader = [Link](file)
# Skip the header row using next()
next(csv_reader, None)
for row in csv_reader:
count += 1
print(f"Total number of records (excluding header): {count}")
count_records()
**********************************************************************************
1. Raj is the manager of a medical store. To keep track of sales records, he has created a CSV
file named [Link], which stores the details of each sale. The columns of the CSV file are:
Product_ID, Product_Name, Quantity_Sold and Price_Per_Unit.
Help him to efficiently maintain the data by creating the following user-defined functions:
I. Accept() – to accept a sales record from the user and add it to the file [Link].
II. CalculateTotalSales() – to calculate and return the total sales based on the
Quantity_Sold and Price_Per_Unit.
Ans- I.
import csv
def Accept():
with open('[Link]', 'a', newline='') as file:
writer = [Link](file)
product_id = input("Enter Product ID: ")
product_name = input("Enter Product Name: ")
quantity_sold = int(input("Enter Quantity Sold: "))
price_per_unit = float(input("Enter Price Per Unit: "))
[Link]([product_id, product_name, quantity_sold, price_per_unit])
print("Sales record added successfully”)
II.
def CalculateTotalSales():
total_sales = 0.0
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
total_sales += int(row[2]) * float(row[3])
print("Total Sal print("Total Sales is:", total_sales)
2. A csv file "[Link]" 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 in the form of a list and display all those records for
which the population is more than 5000000.
(II) Count the number of records in the file.
Ans- (I)
import csv
def show():
f=open("[Link]",'r')
records=[Link](f)
next(records, None)
for i in records:
if int(i[1])>5000000:
print(i)
[Link]()
(II)
import csv
def Count_records():
f=open("[Link]",'r')
records=[Link](f)
next(records, None)
count=0
for i in records:
count+=1
print(count)
[Link]()
3. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created
a csv file named [Link], to store the results of students in different sports events.
The structure of [Link] is : [St_Id, St_Name, Game_Name, Result]
Where St_Id is Student ID (integer) , ST_name is Student Name (string) , Game_Name is name of
game in which student is participating(string). 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:
Accept() – to accept a record from the user and add it to the file [Link]. The column headings
should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As a Python expert, help
him complete the task.
Ans-
def Accept():
sid = int(input("Enter Student ID"))
sname = input("Enter Student Name")
game = input("Enter name of game")
res = input("Enter Result")
headings = ["Student ID", "Student Name", "Game Name", "Result"]
data = [sid, sname, game, res]
f = open('[Link]', 'a', newline = '')
csvwriter = [Link](f)
[Link](headings)
[Link](data)
[Link]()
def wonCount():
f = open('[Link]', 'r')
csvreader = [Link](f, delimiter = ',')
head = list(csvreader)
print(head[0])
for x in head:
if x[3] == "WON":
print(x)
[Link]()
4. Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘[Link]’. Each record consists of a
list with field elements as empid, name and mobile to store employee id, employee name and
employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named ‘[Link]’.
Ans- (i)
import csv
def ADD():
fout=open("[Link]","a",newline="\n")
wr=[Link](fout)
empid=int(input("Enter Employee id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number :: "))
lst=[empid,name,mobile]
[Link](lst)
[Link]()
(ii)
def COUNTR():
fin=open("[Link]","r",newline="\n")
data=[Link](fin)
d=list(data)
print(len(d))
[Link]()
ADD()
COUNTR()