Questions on CSV File Handling in Python
- Categories Python File Handling, Python
In this post we will cover CSV File Handling in Python. You can watch our video on CSV File Handling in Python – Click Here.
Q. 1 What is full form of CSV?
Ans. CSV (Comma Separated Values)
Q. 2 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
Q.3 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
Q. 4 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
Q. 5 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)
Q. 6 Which module is used to operate on CSV file?
Ans. To read and write in CSV files we need to import csv module.
Q. 7 CSV files are opened with __________argument to supress EOL translation.
Ans. newline=’ ‘
Q.8 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 = ‘,’)
Q. 9 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()
Q.10 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 = ‘,’)
Q.11 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. c
Q. 12 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 !’)
Q. 13 What does tell() method do?
Ans. It tells you the current position of cursor within the file
Syntax: file_object.tell()
Q. 14 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
Q. 15 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( ) | Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) fout.seek(5) print(fout.tell( )) fout.close( ) |
Output: 4 | Output: 5 |
Q. 16 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
Ans.
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()
Q. 17 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
Ans.
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( )
Q.18 Write a program to count number of records present in “data.csv” file.
Ans.
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)
Q.19 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
Q. 20 Write a program to copy the data from “data.csv” to “temp.csv”
Ans.
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.21 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', a , newline="");
writer = csv.writer(file)
b open('marks.csv') as csvfile:
data = csv. c (csvfile)
for row in data:
writer.writerow([ d , e ])
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.
Ans.
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()