CSV FILES
• CSV stands for Comma Separated Value.
• CSV is just like a text file, in a human readable format which is extensively used to store tabular data, in a spreadsheet or database.
• The Separator character of CSV file is called a delimiter, Default delimiter is comma (,). Other delimiters are tab (‘\t’), colon (:), semicolon(;) and pipe (|).
CSV File Characteristics :
•
One line for each record
• Comma separated fields
• Space-characters adjacent to
commas are ignored
• Fields with in-built commas are separated by
double quote characters.
When Use CSV?
•
When data has a strict tabular structure
• To transfer large database between programs
• To import and export data to office applications, Qedoc
modules
• To store, manage and modify shopping cart catalogue
CSV Advantages
•
CSV is faster to handle
• CSV is smaller in size
• CSV is easy to generate
• CSV is human readable and easy to edit
manually
• CSV is simple to implement.
• CSV is processed by almost all existing applications
Important functions for handing csv file:
• open() |
is a built-in function to create a file object and to open a CSV file. |
• reader() |
is a function from CSV module and it will read all the records (all the lines) from a CSV file into an iterator object. |
• writer() |
is a function from CSV module and it will create a CSV writer object |
• delimiter |
the default delimiter in a CSV file is comma (,) but using delimiter as an additional parameter with reader() and writer() one can specify a single character string as the delimiter. |
• writerow() |
is a CSV writer object method and it will write data stored in a list(tuple) into a CSV file. |
• writerows() |
is a CSV writer object method and it will write data stored in a nested list(nested tuple) into a CSV file. |
• close() |
is a built-in function to close a CSV file, but if a CSV file is opened using keyword with then there is no need to close the file. |
writer( ) Object Methods –
- w_obj . writerow( <Sequence> ) : Write a Single Line
- w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines
Example:-
## writerow()
import csv
row=['Narain', 'HOD', '2', '9.0']
f=open("ComputerDept.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
## writerows()
import csv
rows = [['Narain','HOD','2','9.0'],
['Priti','PGT','2','9.1']]
f=open("myfile.csv",'w')
w_obj = csv.writer(f)
w_obj.writerows(rows)
f.close()
reader( ) Methods
This function returns a reader object which will be
used to iterate over lines of a given CSV file.
r_obj = csv.reader( csvfile_obj )
To access each row, we have to iterate over this Object.
for i in r_obj:
print(i)
Example:-
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f)
for data in r_obj:
print(data)
f.close()
If we consider the sample.csv file given above in the CSV file structure the output of the above code will be:
## OUTPUT
['Name', 'DOJ', 'City']
['Ram', '12-Jul-2011', ‘Lucknow’]
['Gurmeet', '03-Jan-2008', 'Delhi']
['Prashant', '17-Dec-2009', 'Kolkata']
Problem with writer( ) and Solution
- Extra Newline after each line in CSV File.
- To remove this we have to Open the CSV File
with newline Parameter as Empty '' string:
f=open("myfile.csv", 'w', newline = '') - New Code:
import csv
row=[Narain, 'HOD', '2', '9.0']
f=open("myfile.csv", 'w', newline = '')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
Why Problem with the writer( )
Universal
Newline |
||
'\r' |
Carriage Return |
Mac OS |
'\n' |
Line Feed |
Unix |
'\r\n' |
Carriage Return + New Line |
MS-DOS, Windows |
- Since the CSV module does its own (universal) newline handling. writer() has default line terminator parameter is '\r\n'. When we do not Open the file with newline=''(Empty) python replaces '\r' to '\n'.
- So the newline end will become '\n\n'. That’s why there is an extra newline that will come in CSV.
Writing data using writerow() function
import csv
fw=open('Admission.csv','w')
writer=csv.writer(fw)
writer.writerow(['RollNo','Name','Class'])
record=[]
ch='Y'
while True:
r=input("Enter roll number : ")
nm=input("Enter name : ")
cls=input("Enter class : ")
data=[r,nm,cls]
record.append(data)
ch=input("Do you want to enter more record..? (Y/N) : ").upper()
if ch=='N':
break
for i in record:
writer.writerow(i)
fw.close()
Writing data using writerows() function
import csv
fw=open('Admission.csv','w', newline='')
writer=csv.writer(fw)
writer.writerow(['RollNo','Name','Class'])
record=[]
ch='Y'
while True:
r=input("Enter roll number : ")
nm=input("Enter name : ")
cls=input("Enter class : ")
data=[r,nm,cls]
record.append(data)
ch=input("Do you want to enter more record..? (Y/N) : ").upper()
if ch=='N':
break
writer.writerows(record)
fw.close()
Q1. Kajal Kumari 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): # to write/add data into CSV file
f=open("user.csv') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,Password])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open( user.csv'r') as newFile:
newFileReader = csv._______(new File) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.________________ # Line 4
addCsvFile("Arjun","123@456")
addCsvFile("Arunima","aru@nima")
addCsvFile("Frieda","myname@FRD")
readCsvFile() # Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Kajal should open the file to add data into the file as given in Line 2.
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will get while executing Line 5.
Ans: (a) csv
(b) a
(c) reader
(d) close()
(e) Arjun 123@456
Arunima aru@nima
Frieda myname@FRD
Q2. Teacher has given a program to his students to read a file "datesheet.csv" which contains subject name and date of exam. Sunny is one of the students who has written the following code. As a programmer, help him execute the given task successfully.
import ____________ # Line 1
#csv file reading code
def read_datasheet(): #to read data
fileObj= open(“datesheet.csv", "r"):
fileReader=csv._________(fileObj) # Line 2
for row in _____________ # Line 3
print (row)
fileObj.close()
def create datesheet() # to write data
fileObj=open('datesheet.csv', ‘____’) # Line 4
fileWriter = csv.writer(fileObj)
for i in range(5):
subj=input("Enter subject: ")
date=input("Enter date: ")
fileWriter.writerow(________) #Line 5
fileObj.close()
(a) Name the module which is required to be imported for the given program in Line 1.
(b) For a reader object to complete Line 2.
(c) Complete Line 3 to traverse the data from a CSV file.
(d) What will be added in Line 4 to open a file "datesheet.csv"?
(e) Complete Line 5 to write the data using a writer object.
Ans : (a) csv
(b) reader
(c) fileReader
(d) “w”
(e) [subj, date]
Q3. Khyati is creating a CSV file. "Bark.csv", which will contain bank account number and pin number for hundred customers. The code which is written by her is given below. She did some mistakes in code and left few statements incomplete. Help her to correct the errors and successfully execute the given program.
import pickle # Line 1
def addDetails(): # to write add data into the CSV file
file=open(“e:\atm_bank\bank.csv","a”) #Line 2
writer_obj= csv.writer(file)
for i in range(100):
acc_no=int(input("Enter Ace No."))
pin=input("Enter PIN: ")
cust_rec=[acc_no, pin]
writer obj.writerow(cust rec) # Line 3
file.close()
#csv file reading code
def printDetails(): #to read data from CSV file
file=open(“e\\atm_bank\\bank.csv”, “r”, newline= “\n\r”) # Line
reader_obj=csv.reader(file)
for rec in ____________ # Line 5
print(rec)
file.close()
(a) Correct the module she should import in Line 1.
(b) Correct the syntax error in Line 2.
(c) What is wrong with Line 3, correct it?
(d) Check the problem with newline in Line 4.
(e) Complete the for loop applied in Line 5, so that data can be traversed.
Ans: Corrected code:
import csv # Line 1
def addDetails(): # to write add data into the CSV file
file=open(“e:\\atm_bank\\bank.csv","a”) #Line 2
OR
file=open(r“e:\atm_bank\bank.csv","w”) #Line 2
writer_obj= csv.writer(file)
for i in range(100):
acc_no=int(input("Enter Ace No."))
pin=input("Enter PIN: ")
cust_rec=[acc_no, pin]
writer obj.writerows(cust rec) # Line 3
file.close()
#csv file reading code
def printDetails(): #to read data from CSV file
file=open(“e\\atm_bank\\bank.csv”, “r”, newline= “\r\n”) # Line 4
reader_obj=csv.reader(file)
for rec in reader_obj: # Line 5
print(rec)
file.close()
(a) import csv # Line 1
(b) file=open(“e:\\atm_bank\\bank.csv","a”) #Line 2
OR
(c) file=open(r“e:\atm_bank\bank.csv","w”) #Line 2
(d) writer obj.writerows(cust rec) # Line 3
(e) file=open(“e\\atm_bank\\bank.csv”, “r”, newline= “\r\n”) # Line 4
(f) for rec in readuer_obj: # Line 5
Q4. Priyanshi is writing a program to create a CSV file "game.csv" which contains Game name and number of players. While writing a code she forgot few functions to implement. As a friend, help her to successfully execute the code.
import __________ # Line 1
def Indore games(): # to write and read data with the CSV file
w_file=open('game.csv’, ‘w')
filewriter = csv.writer(w_file, _______) # Line 2
details=[[‘Badminton', 2], ['Care board', 4], [ 'Chess', 2] ]
filewriter.______________(details)
w_file.close() # Line 3
with open(“game.csv”,'r') as r_file:
file_r = csv.reader(____________) # Line 4
for g_name in __________: # Line 5
print(g_name)
Indore_games()
(a) Name the module she should import in Line 1.
(b) Complete Line 2 so that data can be stored into a csv file delimited with pipe character.
(c) Complete Line 3 to write the list of data into a csv file.
(d) Give the argument in reader() function Line 4 to make a reader object.
(e) Complete the for loop statement in Line 5.
Ans:
(a) csv # Line 1
(b) filewriter = csv.writer(w_file, delimiter= ‘|’) #Line 2
(c) writer obj.writerows(details) # Line 3
(d) file_r=csv.reader(r_file) # Line 4
(e) for g_name in file_r: # Line 5
Q5. Akanksha has given the following code to create CSV file "emp.csv" As a programmer, help her to successfully execute the given program.
import ___________ # Line 1
def writeFile(rec): # to write data into the CSV file
file=open(“emp.csv”, __________) # Line 2
filewriter = csv.writer(file)
filewriter._________________(rec) # Line 3
file.close()
#csv file reading code
def readFile(): # to read data from CSV file
file=open(" user.csv', 'r'):
filereader=csv._________________ # Line 4
for row in filereader:
print (row)
file.________ # Line 5
(a) Name the module he should import in Line 1.
(b) Fill Line 2 to open a file in writing mode.
(c) Fill Line 3 to write the record into a csv file.
(d) Fill Line 4 to create the reader object.
(e) Fill Line 5 to close the file.
Ans:
(a) import csv # Line 1
(b) file = open(‘emp.csv’ , ‘a’) #Line 2
(c) filewriter.writerows(rec) # Line 3
(d) filereader=csv.reader(file) # Line 4
(e) file.close() # Line 5
Q6. Dhruv has forgotten few lines while writing a CSV code. Consider the following incomplete code. Help him to complete the code so that it can be run successfully
import csv
def addItem(item_code, item_name): # to write data into the CSV file
_______________________ # Line 1
FileWriter=csv.writer(File)
_______________________([item_code, item_name]) # Line 2
File.close()
#csv file reading code
def readItems(): # to read data from CSV file
File=open(' item.csv','r')
FileReader=_________________ # Line 3
for data in ________: # Line 4
print (data) # Line 5
________________
#main
addItem(11, 'Mouse')
addItem(22, “Keyboard”)
addItem(33, “Printer”)
readItems()
(a) Write the complete statement to open a file in append mode for Line 1.
(b) Fill in the statement to write the data into a file in Line 2.
(c) Create a reader object in Line 3.
(d) In line 4, complete the for loop statement to traverse a data from a file.
(e) Write a statement to close a file in Line 5.
Ans:
(a) File = open(‘item.csv’, ‘a’) # Line 1
(b) FileWriter.writerow([item_code, item_name]) #Line 2
(c) FileReader = csv.reader(File) # Line 3
(d) For data in FileReader: # Line 4
(e) File.close() # Line 5
Q7. Gauri wants to maintain her class list by writing a program in Python. She has created a CSV file "student.csv" which contains student's roll no. and name. As her class mate, help her to complete the task successfully,
import CSV
def write_rows():
#csv file writing a code
data= [[11, 'Anuj'], [12, 'Neha'], [13, 'Sehej']]
File = open('stutent.csv’ ‘_______’) # Line 1
FW= csv.writer(File)
FW.__________________(data) # Line 2
File.close()
#csv file reading a code
def read_rows():
__________________ as File: # Line 3
FR = csv.reader(File,____________) # Line 4
for row in FR:
print(_____, _______) # Line 5
File.close()
(a) Suggest the code to open the file is writing mode in Line 1.
(b) Write a suitable function to write a data into a file 'student.csv' in Line 2.
(c) Write a statement to open a csv file 'student.csv' in reading mode by using open with function in Line 3.
(d) Give delimiter to separate values or fields by pipe operator in Line 4.
(e) Complete the Line 5, so that data can be displayed on screen.
Ans:
(a) File = open(‘student.csv’, ‘a’) # Line 1
(b) FW.writerows(data) # Line 2
(c) With open(“student.csv”, ‘r’) # Line 3
(d) FR = =csv.reader(File, delimitere =’|’ # Line 4
(e) print(row[0], row[1]) # Line 5
Q8. Himneesh is preparing for pre-board examinations. His teacher has given a code in Python to read and write data using CSV file. He has written the following code but it is complete. As a friend, help him to complete the code so that it can be executed successfully.
import csv
file_obj = open("e:"time_table"XII_A.csv") # Line 1
writer_obj = file_obj.writer(csv) # Line 2
for i in range(3):
r = int(input("Enter roll no.:"))
n = input("Enter name:")
m = int(input("Enter marks:"))
record=[r, n, m]
writer_obj.writerows(record) # Line3
file_obj.close()
file_obj = open("e: \time_table\XII_A1.csv", "r") # Line 4
reader_obj = csv.reader(file_obj)
for rec in reader_obj:
print(rec)
reader_obj.close() # Line 5
(a) Identify and write the correct statement for Line 1
(b) Check Line 2 and detect the error in writer() function.
(c) Write the correct statement to obtain the output for Line 3.
(d) Correct the statement given in Line 4, why open function is showing an invalid argument error?
(e) In Line 5, close the file properly after reading a csv file.
Ans:
(a) file_obj = open("e:\\time_table\\XII_A.csv", “w”) # Line 1
(b) writer_obj = csv.writer(file_obj) #Line 2
(c) writer_obj.writerow(record) # Line 3
(d) file_obj = open("e:\\time_table\\XII_A1.csv", "r") # Line 4
OR
file_obj = open(r"e:\time_table\XII_A1.csv", "r") # Line 4
(e) file_obj.close() # Line 5
Q9. Sankalp Saxena is a 2nd year student of a University. He has created a CSV file "Project.csv" which stores the state wise report of population of India. As faculty, check and help him in the completion of code written by him.
import csv
#Function to write a data
def addCsvFile(state, population):
with open('Project.csv', 'a') ___________: # Line 1
fwriter = csv.writer(file)
fwriter.writerow(______________) # Line 2
#Function for reading a data
def readCsvFile():
with open(‘Project.csv', 'r') as file:
freader = csv._____________(file) # Line 3
for row in freader:
print(_____, ______) # Line 4
#_main_
_________________ #Line 5
readCsvFile() # function call to print the record.
(a) To declare the file object in Line 1.
(b) To write the data into a csv file in Line 2.
(c) Create the reader object in Line 3
(d) To display record on the screen in Line 4.
(e) Complete the statement in Line 5, so that the function addCsvFile() can be invoked
Ans:
import csv
#Function to write a data
def addCsvFile(state, population):
with open('Project.csv', 'a') as file: # Line 1
fwriter = csv.writer(file)
fwriter.writerow([state, population]) # Line 2
#Function for reading a data
def readCsvFile():
with open(‘Project.csv', 'r') as file:
freader = csv.reader(file) # Line 3
for row in freader:
print(row[0], row[1]) # Line 4
#_main_
addCsvFile(UP, 200000000) #Line 5
readCsvFile() # function call to print the record.
(a) with open('Project.csv', 'a') as file: # Line 1
(b) fwriter.writerow([state, population]) #Line 2
(c) freader = csv.reader(file) # Line 3
(d) print(row[0], row[1]) # Line 4
(e) addCsvFile(UP, 200000000) # Line 5
Q10. The school is hosting an inter school event 'Unnat’. The Event head of the school has written the following program to create a CSV file "student.csv” which will store the participating school entries such as Event number, Event name and number of participants. As a programmer, help him to successfully execute the given task.
____________________ # Line 1
def input_details(): # to write/add data into the CSV file
file = open('unnat.csv","") # Line 2
writer_obj = csv.writer(file, _________) # Line 3
writer_obj.writerow(['Event_No’, ‘Event_Name’, 'No_of_participaints']) #Header
e_no= int(input("Enter event no.:”))
e_name = input("Enter event name: ")
p_no = int(input("Enter no. of participant:'))
rec = [e_no, e_name, p_no]
______________________ # Line 4
f.close()
#csv file reading code
def print_details(): # to read data from CSV file
with open('unnat.csv', 'r') as file:
reader_obj = ______________ # Line 5
for rec in reader_obj:
print (rec)
(a) Name the module he should import in Line1.
(b) In line 2, give the writing mode.
(c) Specify the tab delimiter in Line 3.
(d) Complete Line 4 to write data into a
(e) To create the file reader complete the code in Line 5.
Ans:
(a) import csv # Line 1
(b) file = open(‘unnat.csv’ , ‘w’) #Line 2
(c) writer_obj = csv.writer(file, delimiter = ‘\t’) # Line 3
(d) writer_obj.writerow(rec) # Line 4
(e) reader_obj = csv.reader(file) # Line 5
Q11. Armeet has created a CSV file "Info.csv" to store her office details. Later she realized to make another copy of same content for safer side. She tried to write the code in order to make a copy of existing file but not able to write correct code. Being a friend, help her to correct the code so that she can have a duplicate copy of file "Info.csv".
______________________ #Line 1
File1 = open("Info.csv","r",newline="\r\n")
file2 = open("Info2.csv", "____") #Line 2
reader_obj = file1.reader(csv) # Line 3
writer_obj csv._____________ (file2) # Line 4
for rec in reader_obj:
writer_obj.writerows(rec) # Line 5
file1.close()
file2.close()
(a) She forgets to import the module in Line 1, write a statement to import a relevant module.
(b) She also forgets to specify the writing mode. Fill in the blank to specify the writing mode in Line 2.
(c) Find out the problem and correct the statement of Line 3.
(d) Create the writer object in Line 4.
(e) In Line 5, writerows() function is creating a problem in writing a data into the file.
Detect the problem and rewrite the statement of Line 5.
Ans:
(a) import csv # Line 1
(b) file2 = open(‘Info.csv’ , ‘w’) #Line 2
(c) reader_obj= csv.reader(file1) # Line 3
(d) writer_obj=csv.writer(file2) # Line 4
(e) writer_obj.writerow(rec) # Line 5
Q12. Gurmeet has created a CSV file "myfile.csv" but he is unable to run the code. As a programmer, help him to fill the given blanks to execute the program successfully
from csv import ______________, _____________ #Line 1
def writeFile(rec): #function to write data into a file.
file = open('myfile.csv’ , ‘_____’) # Line 2
filewriter = ________________(file) # Line 3
filewriter.writerow(rec)
file.close()
def readFile(): # to read data from CSV file
file = open(" myfile.csv', 'r’):
filereaders = ________________(file) # Line 4
for row in filereader:
print(______________) # Line 5
file.close()
#__main__
rec =[ 1101, "Mouse"]
writeFile(rec)
rec = [2201, "Keyword"]
writeFile(rec)
writeFile(rec)
readFile()
(a) Name the functions that should be imported in Line 1.
(b) Suggest the mode to write more records with the continuation of already existing records.
(c) Fill the Line 3, so that file writer object can be enabled to write data into a “myfile.csv” file.
(d) Complete the Line 4, so that data can be fetched from a "myfile.csv” file.
(e) Fill the Line 5 to display the data on screen.
Ans:
(a) from csv import reader, writer #Line 1 (some time showing error)
OR
from csv import * # Line 1 (some time showing error)
OR
import csv # Line 1
(b) w #Line 2
(c) filewriter = csv.writer(file) # Line 3
(d) filereader=csv.reader(file) # Line 4
(e) print(row[0],row[1], sep=’\t’) # Line 5
Q13. Mansha Srivastava is learning Python programming from the internet. While practicing the CSV code, she forgot to write a few statements. Help her in completing the given below statements.
import csv
def addRect(): #1 to write data into the CSV file
____________________ #Line 1
csvWriter = csv.writer(___________) #Line 2
eno = int(input(“ Enter emp No "))
ename = input("Enter name")
____________________([eno, ename]) #Line 3
File.close()
def showRec(): #to read data from CSVle
file = open(“emp.csv”, “r”)
csvReader = csvReader(file) # Line 4
for __________ in csvReader: # Line 5
print (rec)
file.close()
#__main__
addRect()
showRec()
(a) Using 'with open' function create a file "emp.csv" in writing mode for Line 1.
(b) Complete the Line 2, to create the csv reader object.
(c) Write a record into a csv file, entered by user in Line 3.
(d) In Line 4, csv Reader is creating a problem, check and correct it.
(e) Fill the blank of Line 5 so that data can be traversed.
Ans:
(a) File = open(‘emp.csv’ , ‘w’) # Line 1
(b) csvWriter = csv.writer(File) #Line 2
(c) csvWriter.writerow([eno, ename]) #Line 3
(d) csvReader=csv.reader(File) # Line 4
(e) for rec in csvReader # Line 5
Q14. Avin has forgotten a few lines while writing a CSV code Consider the following incomplete code. Help him so that the code can be run successfully.
import csv
def addPatientDetails(p_name, p_disease): # function definition to write data
csvFileObj = _____________________ #Line 1
fileWriter = ______________________ # Line 2
rec = _____________________________ # Line 3
fileWriter.___________________(rec) # Line 4
csvFileObj._____________ # Line 5
#___main___
addPatientDetails("Pawan", "Typhoid")
add Patient Details("Neeru", "Pneumonia")
(a) Open a file "patient.csv" in writing mode for Line 1.
(b) Write a statement to create a writer object for Line 2.
(c) Complete Line3, to initialize a variable rec as a list with data passed as an argument.
(d) In line 4, write a data into a file "patient.csv" using a reference of "fileWriter" object.
(e) Write a statement to close a file in Line 5.
Ans:
(a) open(‘patient.csv’, ‘w’) # Line 1
(b) csvWriter = csv.writer(csvFileObj) #Line 2
(c) rec=[p_name,p_disease] #Line 3
(d) csv.writer # Line 4
(e) csvFileObj.close() # Line 5
Q15. Consider the following incomplete CSV code to write the list of items into a "ITEM.CSV file. Perform the following tasks so that the code can be executed successfully.
_____________________________ #Line 1
def addNewArrivals(itemList): # itemList is list of items
___________________ # Line 2
fileWriter = ___________________ (File) # Line 3
for _________ in itemlist: # Line 4
_______________.writerow(item) # Line 5
(a) Write a statement to import a relevant module for Line 1
(b) In Line 2, open a file to append data into a file "ITEM.CSV” file.
(c) Create a writer object in Line 3.
(d) In Line 4, provide a relevant variable in for loop to traverse a data from a file.
(e) In Line 5, give a reference to writerow() function so that list of data can be written into a file one by one.
Ans:
(a) import csv # Line 1
(b) with open(“ITEM.CSV”, ‘a’) as File: #Line 2
(c) csv.writer(File) #Line 3
(d) item # Line 4
(e) FileWriter # Line 5
Q16. Anuj has been assigned a program to write a table in CSV file from 2 to 20 by his teacher. He tried to write a code for it but he got confused to implement full code and also he did some mistakes. Let's help him so that he can submit the code to his teacher.
import csv
file_obj = _______________________________ # Line 1
writer_obj = csv.writer(file_obj)
for i in range (___________,____________): # Line 2
record=[]
for j in range(2,11):
val = i*j
record.append(val)
writer_obj._______________ # Line 3
file_obj.close()
file_obj=open("table.csv", "r")
reader_obj = csv.reader(file_obj)
for a in ________________________: # Line 4
for b in a:
print(a,end= “ “) # Line 5
print()
file_obj.close()
(a) Complete Line1, to create a file "Table.csv" in writing file.
(b) In Line2, set a 'for' loop with initial and targeted values.
(c) Write a function in Line3, to write a list containing calculated value.
(d) For Line 4 complete the for loop.
(e) In Lines, correct table is not printing on screen, identify the problem make necessary corrections.
Ans:
(a) open("Table.csv",'w', newline='\n') # Line 1
(b) 1,11 #Line 2
(c) .writerow(record) #Line 3
(d) for a in reader_obj: # Line 4
(e) print(b,end= " ") # Line 5
Programs python CSV
[1] Read a CSV file
top5.csv and print the contents in a proper format. The data for top5.csv file
are as following:
SNo |
Batsman |
Team |
Runs |
Highest |
1 |
K L Rahul |
KXI |
670 |
132* |
2 |
S Dhawan |
DC |
618 |
106* |
3 |
David Warner |
SRH |
548 |
85* |
4 |
Shreyas Iyer |
DC |
519 |
88* |
5 |
Ishan Kishan |
MI |
516 |
99 |
Solution:
from csv import reader
def pro1():
with
open("top5.csv","r") as f:
d = reader(f)
data=list(d)
for i in data:
print(i)
pro1()
[2] Read a CSV file emp.csv
and print the contents as it is without list brackets.
EmpCode |
EName |
Post |
Salary |
Department |
1001 |
Shobhit |
Manager |
55000 |
Finance |
1002 |
Manmit |
Clerk |
35000 |
Office |
1003 |
Sujal |
Development Officer |
65000 |
R & D |
1004 |
Manisha |
Tele Caller |
42000 |
Communication |
1005 |
Gayatri |
System Analyst |
53000 |
Software |
Solution:
from csv import reader
def pro2():
with
open("emp.csv","r") as f:
d = reader(f)
data=list(d)
for i in data:
print(','.join(i))
pro2()
[3] Read a CSV file
students.csv and print them with tab delimiter. Ignore first row header to
print in tabular form.
RollNo |
Name |
Score |
1 |
Aviral |
54 |
2 |
Manoj |
87 |
3 |
Sachin |
98 |
4 |
Anchit |
43 |
5 |
Jyoti |
87 |
Solution:
from csv import reader
def pro3():
f =
open("students.csv","r")
dt =
reader(f,delimiter=',')
headr_row=next(dt)
data =
list(dt)
f.close()
for i in
data:
for j in i:
print(j,"\t",end=" ")
print()
pro3()
[4] Write records of
customer into result.csv. The fields are as following:
Field 1 |
Data Type |
StudentID |
Integer |
StudentName |
String |
Score |
Integer |
Solution:
from csv import writer
def pro4():
#Create Header First
f =
open("students.csv","w",newline='\n')
dt =
writer(f)
dt.writerow(['Student_ID','StudentName','Score'])
f.close()
#Insert
Data
f =
open("students.csv","a",newline='\n')
while
True:
st_id= int(input("Enter Student ID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or Y):")
ch=ch.lower()
if ch !='y':
break
print("Record has been added.")
f.close()
pro4()
[5] Read and print above
file contents in the form dictionary.
Solution:
import csv
data =
csv.DictReader(open("students.csv"))
print("CSV file as a
dictionary:\n")
for row in data:
print(row)
[6] Read Students name and
score from the CSV file.
Solution:
import csv
with open('students.csv',
newline='') as f:
data =
csv.DictReader(f)
print("Student Name","\t", "Score")
print("*"*50)
for i in
data:
print(i['StudentName'], "\t",i['Score'])
[7] Count the number of
records and column names present in the CSV file.
Concepts used:
1. Skip first row using next()
method
2. line_num properties used to
count the no. of rows
Solution:
import csv
def pro7():
fields =
[]
rows =
[]
with
open('students.csv', newline='') as f:
data = csv.reader(f)
# Following command skips the first row of CSV file
fields = next(data)
print('Field names are:')
for field in fields:
print(field, "\t")
print()
print("Data of CSV File:")
for i in data:
print('\t'.join(i))
print("\nTotal no. of rows: %d" %(data.line_num))
pro7()
[8]. Write a program to write into file “one.csv” Rollno, Name and Marks separated by comma. It should have header row and then take in input from the user for all following rows. The format of the file should be as shown if user enters 2 records.
Roll.No,Name,Marks
20,ronit,67
56,nihir,69
Solution.
import csv
f1=open('one.csv','w',newline=‘ ')
w1=csv.writer(f1,delimiter = ",")
w1.writerow(['Roll.No', 'Name', 'Marks'])
while True:
print ("Enter 1 to
continue adding, 0 to exit")
op = int(input("Enter
Option"))
if (op == 1):
rollno = int(input("Enter Roll No"))
name = input("Enter Name")
marks = int(input("Enter Marks"))
wlist = [rollno,name,marks]
w1.writerow(wlist)
elif op == 0:
break;
f1.close()
[9]. Write a program to read all content of
“student.csv” and display records of only those students who scored more than
80 marks. Records stored in students is in format : Rollno, Name, Marks
Solution.
import csv
f=open("student.csv","r")
d=csv.reader(f)
next(f)
print("Students Scored More than 80")
print()
for i in d:
if int(i[2])>80:
print("Roll Number =", i[0])
print("Name =", i[1])
print("Marks=", i[2])
f.close( )
[10] Write a program
to count number of records present in “data.csv” file.
Solution.
import csv
f = open("data.csv" , "r")
d = csv.reader(f)
next(f) #to skip header row
r = 0
for row in d:
r = r+1
print("Number of records are " , r)
[11] What is the
output of the following program if the student.csv file contains following
data?
Student.csv
Ronit, 200
Akshaj, 400
Program
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
Solution.
Akshaj, 400
[11] Write a program
to copy the data from “data.csv” to “temp.csv”
Solution.
import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
Q. Create CSV file using dictionary[Menu Driven]Download Source Code
import csv
#Create CSV file using Dictionary
def create():
fw=open("Info.csv",'w', newline='')
cols=['RegNo','Name','Stream']
writer=csv.DictWriter(fw,fieldnames=cols)
writer.writeheader()
rec=[]
while True:
r=input("Registration No. :")
nm=input("Name of Student :")
st=input("Stream :")
rec.append({'RegNo':r,'Name':nm,'Stream':st})
ch=input("Add more Records (y/n)").lower()
if ch=='n':break
writer.writerows(rec)
fw.close()
def show():
fr=open("Info.csv",'r')
reader=csv.DictReader(fr)
print('RegNo','Name','Stream',sep='\t')
print("="*22)
for rec in reader:
print(rec['RegNo'],rec['Name'],rec['Stream'],sep='\t')
fr.close()
#Search Data Streamwise
def Search(): #stream
fr=open("Info.csv",'r')
reader=csv.DictReader(fr)
st=input("Enter Stream :")
print('RegNo','Name','Stream',sep='\t')
print("="*22)
found=False
for rec in reader:
if rec['Stream']==st:
print(rec['RegNo'],rec['Name'],rec['Stream'],sep='\t')
found=True
print("="*22)
if found==False:
print("Record not found...")
fr.close()
#Counts Stream
def count(): #stream
st=input("Enter Stream :")
fr=open("Info.csv",'r')
reader=csv.DictReader(fr)
print('RegNo','Name','Stream',sep='\t')
print("="*22)
count=0
for rec in reader:
if rec['Stream']==st:
print(rec['RegNo'],rec['Name'],rec['Stream'],sep='\t')
count+=1
print("="*22)
print("No.of",st,"candidates: ",count)
fr.close()
# Create file streamwise from main file.
def copy():
fr=open("Info.csv",'r')
st=input("Enter Stream :")
fw=open(st+'.csv','w',newline="")
cols=['RegNo','Name','Stream']
writer=csv.DictWriter(fw,fieldnames=cols)
writer.writeheader()
reader=csv.DictReader(fr)
rec1=[]
for rec in reader:
if rec['Stream']==st:
rDict={'RegNo':rec['RegNo'],'Name':rec['Name'],'Stream':rec['Stream']}
rec1.append(rDict)
print(rec1)
writer.writerows(rec1)
fw.close()
fr.close()
while True:
ch=int(input("1.Create\n2.Show\n3.Search\n4.Count Stream\n5.Copy Stream\n6.Exit\nEnter choice(1-6) : "))
if ch==1:create()
if ch==2:show()
if ch==3:Search()
if ch==4:count()
if ch==5:copy()
if ch==6:break
No comments:
Post a Comment