Exam Questions On CSV File in Python
- Categories Python, Python File Handling
What is full form of CSV?
Ans. CSV (Comma Separated Values)
What is CSV file? What are its characteristics?
Ans.
- CSV (Comma Separated Values) is a file format for data storage which looks like a text file.
- It is used to store tabular data, such as a spreadsheet or database.
- The information is organized with one record on each line
- Each field is separated by comma.
- You can choose a different delimiter character such as ‘ ‘:’ , ‘;’ , ‘|’.
- In CSV files space-characters adjacent to commas are ignored
When do we use CSV file?
Ans.
- When data has a strict tabular structure
- To transfer large data between programs
- To import and export data
What are the Advantages of CSV files?
Ans. Advantages of CSV:
• CSV is faster to handle
• CSV is smaller in size and is easy to generate
• CSV is human readable and easy to edit manually
• CSV is simple to implement and parse
• CSV is processed by almost all existing applications
What are the Disadvantages of CSV files?
Ans. Disadvantages of CSV:
• There is no standard way to represent binary data
• There is no distinction between text and numeric values
• There is poor support of special characters and control characters
• CSV allows to move most basic data only. Complex configurations cannot be imported and exported this way
• There are problems with importing CSV into SQL (no distinction between NULL and quotes)
Which module is used to operate on CSV file.
Ans. To read and write in CSV files we need to import csv module.
CSV files are opened with __________argument to supress EOL translation.
Ans. newline=’ ‘
What does csv writer() function do?
- Ans.
The csv.writer() function returns a writer object that converts the user’s data into a delimited string. - This writer object can be used to write into CSV files using the writerow() function.
- Syntax :
writerobj = csv.writer(filehandle, delimiter=’ ‘)
Where filehandle = filehandle returned from open() function
delimiter = delimiter to be used to separate columns
- e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
What is the difference between writer object’s writerow() and writerows() function?
Ans.
writer.writerow(row)
- Write the row parameter to the writer’s file object, formatted according to delimiter defined in writer function
- e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
f1.close()writer.
writerows(rows)
- Writes multiple rows (sequence) to the writer’s file object
- e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]])
f1.close()
What is csv reader() function?
Ans.
- The csv.reader () function returns a reader object that helps in reading rows as per the delimiter specified.
- This reader object is used to iterate over lines in the given csvfile.
- Each row read from the csv file is returned as a list of strings.
- Syntax :
readerobj = csv.reader(filehandle, delimiter=’,‘)
Where filehandle = filehandle returned from open() function
delimiter = delimiter to be used to separate columns
- e.g.
import csv
f1=open(‘one.csv’,‘r’)
w1=csv.reader(f1,delimiter = ‘,’)
Which of the following file types can be opened with notepad as well as ms excel?
- Text Files
- Binary Files
- CSV Files
- None of these
Ans. 3
What is with statement in Python?
Ans.
- with statement in Python is used in to simplify the management of common resources like file streams.
- It make the code cleaner and much more readable.
- For e.g. there is no need to call file.close() when using with statement.
- e.g.
with open('file_path', 'w') as file:
file.write('hello world !')
What does tell() method do?
Ans.
- It tells you the current position of cursor within the file
- Syntax: file_object.tell()
What does seek() method do?
Ans.
- Seek() method can be used to changes the current file position
- Syntax: Fileobject.seek(offset[, from])
Offset: number of bytes to be moved.
From: 0 – Beginning of the file
1 – Current Position
2 – End of the file
What is difference between tell() and seek() methods
Ans.
tell() | seek() |
---|---|
It returns the current position of cursor in file. | Change the cursor position by bytes as specified by the offset. |
Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) print(fout.tell( )) fout.close( ) Output: 14 | Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) fout.seek(5) print(fout.tell( )) fout.close( ) Output: 5 |
WRITE PROGRAMS
Write a program to write Customer code,Customer name and Amt in file “cust.csv”.
import csv
f1 = open('cust.csv', 'w', newline = '')
w1 = csv.writer(f1, delimiter = ";")
w1.writerow(['CustCode', 'CustName', 'Amount'])
w1.writerow(['001', 'Nihir', '8000'])
w1.writerow(['104', 'Akshay', '5000'])
f1.close()
Write a program to append Customer code,Customer name and amt in file “cust.csv”.
import csv
f1 = open('cust.csv', 'a', newline = '')
w1 = csv.writer(f1, delimiter = ";")
w1.writerow(['001', 'Nihir', '8000'])
w1.writerow(['104', 'Akshay', '5000'])
f1.close()
Write a program to take in Rollno, name and marks of student from user and write to file“student .csv”.
import csv
f1 = open('student.csv', 'w', newline = '')
w1 = csv.writer(f1, delimiter = ",")
w1.writerow(['RollNo', 'Name', 'Marks'])
while True:
op = int(input("Enter 1 to add and 0to exit"))
if(op == 1):
rollno = input("Enter Roll No: ")
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
w1.writerow([rollno, name, marks])
elif op == 0:
break
f1.close()
Write a program to append to file“student .csv”.
import csv
f1 = open('student.csv', 'a', newline = '')
w1 = csv.writer(f1, delimiter = ",")
while True:
op = int(input("Enter 1 to add and 0to exit"))
if(op == 1):
rollno = input("Enter Roll No: ")
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
w1.writerow([rollno, name, marks])
elif op == 0:
break
f1.close()
Write a program to open "xyz.csv" file and write book no, book name and no of pages with separator as tab.
import csv
f1 = open('xyz.csv', 'w', newline = '')
w1 = csv.writer(f1, delimiter = "\t")
w1.writerow(['BookNo', 'BookName', 'Pages'])
while True:
op = int(input("Enter 1 to add and 0to exit"))
if(op == 1):
Bookno = int(input("Enter Book No: "))
Bookname = input("Enter Book Name: ")
Pages = int(input("Enter Pages: "))
w1.writerow([Bookno, Bookname, Pages])
elif op == 0:
break
f1.close()
Read or Search Programs
Write a program to count number of records present in “data.csv” file.
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)
f.close()
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);
Ans. Akshaj, 400
Write a program to display all contents of the file.
RollNo, Name, Marks
1, Nilesh, 65
2, Akshay, 75
import csv
f = open("student.csv", 'r')
r = csv.reader(f, delimiter = ',')
for row in r :
print(row)
f.close()
Write a program to display only roll no and student name of the file.
RollNo, Name, Marks
1, Nilesh, 65
2, Akshay, 75
import csv
f = open("student.csv", 'r')
r = csv.reader(f, delimiter = ',')
for row in r :
print(row[0], row[1])
f.close()
Write a program to Search and Print only Roll no and student marks of the file.
RollNo, Name, Marks
1, Nilesh, 65
2, Akshay, 75
import csv
f = open("student.csv", 'r')
r = csv.reader(f, delimiter = ',')
for row in r :
print(row[0], row[2])
f.close()
A file customer.csv contains a city, customer name and amount. Search and print all rows where city is “delhi”.
Sample customer.csv :
City, Cust Name, Amount
Delhi, Anil Sharma, 10000
Pune, Mr Dua, 20000
Delhi, Mr Das, 25000
import csv
f = open("customer.csv", 'r')
r = csv.reader(f, delimiter = ',')
for row in r :
if row[0].lower()=="delhi :
print(row[1], row[2])
f.close()
Q. A file customer.csv contains a city, customer name and amount. Print all rows where customer name is “Anil”.
Sample customer.csv :
City, Cust Name, Amount
Delhi, Anil Sharma, 10000
Pune, Mr Dua, 20000
Delhi, Mr Das, 25000
import csv
f = open("customer.csv", 'r')
r = csv.reader(f, delimiter = ',')
for row in r :
if "Anil" in row[1] :
print(row[1], row[2])
f.close()
A file customer.csv contains a city, customer name and amount for all sales more than 15000. S
Sample customer.csv :
City, Cust Name, Amount
Delhi, Anil Sharma, 10000
Pune, Mr Dua, 20000
Delhi, Mr Das, 25000
import csv
f = open("customer.csv", 'r')
r = csv.reader(f, delimiter = ',')
next(f)
for row in r :
if int(row[2]) > 15000 :
print(row[1], row[2])
f.close()
Read + Write Programs
Write a program to copy the data from “data.csv” to “new.csv” and separator is comma in both the file.
import csv
f1 = open("data.csv", 'r')
f2 = open("new.csv", 'w', newline = '')
r1 = csv.reader(f1)
w1 = csv.writer(f2)
for row in r1 :
w1.writerow(row)
f1.close()
f2.close()
File data.csv has come from branch in Pune and it needs to added to file “new.csv” to which has data for all branches.
import csv
f1 = open("data.csv", 'r')
f2 = open("new.csv", 'a', newline = '')
r1 = csv.reader(f1)
w1 = csv.writer(f2)
for row in r1 :
w1.writerow(row)
f1.close()
f2.close()
A file data.csv has come with separator ':' but your system can only read ';' Write a progam to convert to “new.csv” file. Write a program to change the separator of the file.
import csv
f1 = open("data.csv", 'r')
f2 = open("new.csv", 'w', newline = '')
r1 = csv.reader(f1, delimiter = ":")
w1 = csv.writer(f2, delimiter = ";")
for row in r1 :
w1.writerow(row)
f1.close()
f2.close()
Ronit has a CSV file “marks.csv” which has name, class and marks separated by comma. He is writing a Python program to copy only the name and class to another CSV file “class.csv”. He has written the following code. As a programmer, help him to successfully execute the given task.
import csv
file = open('class.csv', 1 , newline="")
writer = csv.writer(file)
2 open('marks.csv') as csvfile:
data = csv. 3 (csvfile)
for row in data:
writer.writerow([ 4 , 5 ])
file.close()
- In which mode should Ronit open the file to make a new file?
- Which Python keyword should be used to manage the file stream?
- Fill in the blank in Line 3 to read the data from a csv file.
- Fill in the blank to write name into marks.csv
- Fill in the blank to write class into marks.csv.
import csv
file = open('class.csv','w', newline="")
writer = csv.writer(file)
with open('marks.csv') as csvfile:
data = csv.reader(csvfile)
for row in data:
writer.writerow([row[0],row[1]])
file.close()
Ronit has a CSV file “marks.csv” which has name, class and marks separated by comma. He is writing a Python program to copy only rows of students of class 2 to another CSV file “class.csv”. He has written the following code. Help him to successfully execute the given task.
import csv
file = open('class.csv', 'w' , 1 )
w1 = 2 (file)
with open('marks.csv') as 3 :
data = csv. reader(csvfile)
for row in data:
if 4 == '2' :
writer. 5 (row)
file.close()
- While opening the file what needs to be added to suppress extra EOL during writing?
- Which csv function is used to return an object to be used for writing into a file?
- Fill in the bank with the name of the filehandle to be used.
- Fill in the blank to select the right field which needs to be compared with 2.
- Fill in the blank with correct function to write in csv file.
import csv
file = open('class.csv', 'w' ,newline="")
w1 = csv.writer(file)
with open('marks.csv') as csvfile:
data = csv. reader(csvfile)
for row in data:
if row[1]== '2' :
writer.writerow(row)
file.close()