File_Handling
File_Handling
File_Handling
5) returns a
value close to 3j.
FILE HANDLING
Files are of bytes stored on storage devices such as hard-disks. Files help in storing
information permanently on a computer.
Data Files:
Data files are files that store data pertaining to a specific application. The data files
can be stored in following ways:
• Text files: These files store information in the form of a stream of ASCII or UNICODE
characters. Each line is terminated by an EOL character. Python programs, contents written
in text editors are some of the example of text files.
• Binary files: These files store information in the form of a stream of bytes. No EOL character
is used and binary files hold information in the same format in which it is held in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of binary
files.We can’t read a binary file using a text editor.
Difference Between Text File And Binary File
Text File Binary File
Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
Less prone to get corrupt as change reflects as Can easily get corrupted, corrupt on even single
soon as made and can be undone. bit change.
Store only plain text in a file. Can store different types of data.
Widely used file format and can be opened in Developed for an application and can be
any text editor. opened in that only.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opened in any text editor. Mostly .txt and .rtf Can have any application defined extensions.
are used as extensions of text files.
• Please note that when you open a file in read mode,the given file must exist in folder,
otherwise Python will raise error.
File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it
available for a number of different tasks.
FileAccessModes:-
Text Binary
Description
file File
mode Mode
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the file
does not exist.
‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does not
exist
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it does
not exist
‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.
73
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it
refers to how the file will be used once it's opened.
Closing Files :
One must always close a file when the file is no longer required for any more
operations.The file can be closed by using the close( ) function which can be used w ith the
file pointer as follows:
<file_handle>.close()
Working with Text Files:
1. Read the data from a file
2. Write the data to a file
3. Append the data to a file
OUTPUT:
Example-1:Programusingread()function:
fin=open("D:\\pythonprograms\\Boo Python is interactive language. It is case sensitive
k.txt",'r') language.
str=fin.read( ) It makes the difference between uppercase and
74
print(str) lowercase letters. It is official language of google.
fin.close()
Example-2:Programusingread()function: OUTPUT:
fin=open("D:\\python programs\\Book.txt",'r')
Python is
str=fin.read(10)
print(str)
fin.close()
Example-3:usingreadline()function: OUTPUT:
Myfile
I am Peter.
How are you?
OUTPUT:
Example-1:Program using write()function:
My name is Aarav.
f=open(r’MyFile.txt’,’w’)
data = ‘My name is Aarav.’
f.write(data)
f.close( )
f=open(r’MyFile.txt’,’r’)
data = f.read( )
75
print(data)
f.close( )
flush( ) function:
• When we write any data to file, python hold everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to force Python to write the content of buffer onto
storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it will be implicitly called by the
close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the opened
file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to place
the file pointer. The mode argument is optional and has three possible values namely 0, 1
and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as
follows:
f.tell()
76
OUTPUT:
Example-1: tell()function:
Example: fout=open("story.txt","w") 14
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )
WORKSHEET
LEVEL-I
7 Write a python program to accept a line from the user and store that in a file
2
“story.txt”.
8 Write a function to copy all the upper case words to another file. 2
9 Write the function to read the content from the file display the word which are having
3
the length of exactly 4 characters.
10 Krishna is confused in Python code given below. Please help him to answer the
5
following questions.
77
(a) Which line in the above code check for capital letter?
(b) Which line in the above code read the file “story. txt”?
(c) Which line in the above code does not affect the execution of program?
(d) Which line is the above code coverts capital letter to small letter?
(e) Which line is the above code opens the file in write mode?
(f) Which line is the above code saves the data?
(g) Which line(s) is/are the part of selection statement.
(h) Which line(s) is/are used to close story1.txt?
ANSWERS
1 (b) file_read = open("c:marks.txt", "r")
2 (a) returns the current position of record pointer within the file
3 (a) File.read(n)
4 (b) File object = open(file_name [, access_mode][,buffering])
6 22
7
78
8
(a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7 (e) Line 2 (f) Line 13 (g) Line 6, Line 8
10
and Line 11 (h) Line 15
LEVEL-2
1 To read two characters from a file object "file_read"
(a) file_read.read(2)
(b) file_read(2) 1
(c) file_read(read,2)
(d) file_read.readlines(2)
2 seek() method in files used for 1
3 What does the <readlines()> method returns? (a) Str (b) A list of lines(c) List of single
1
characters(d) List of integers
4 Differentiate the following:
(a) f = open('diary.txt', 'r') 1
(b) f = open('diary.txt', 'w')
79
5 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be
ANSWERS
1 (a) file_read.read(2)
2 Sets the file's current position at the offset
3 (b) A list of lines
(a) It opens the file in reading mode only in text format.
4 (b) It opens the file in writing mode only in text format. If the file exists, then it erases
the previous data.
80
5 13
5 Write a method in Python to read lines from a text file INDIA.TXT, to find and
6
Write a function to read the content from the file “India.txt”, and store the frequency
of each word in dictionary and display the dictionary in the screen.
Content of the file is:
‘‘India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
4
Most of the Indians can foresee the heights that India is capable of reaching.’’
Output of the file:
{‘India’: 4, ‘is’: 4, ‘the’: 4, ‘fastest’: 1, ‘growing’: 1, ‘economy.’: 1, ‘looking’: 2,
‘for’: 1, ‘more’: 1, ‘investments’: 1, ‘around’: 1, ‘globe.’: 1, ‘The’: 1, ‘whole’: 1,
‘world’: 1, ‘at’: 1, ‘as’: 1, ‘a’: 1, ‘great’: 1, ‘market.’: 1, ‘Most’: 1, ‘of’: 2, ‘Indians’:
1, ‘can’: 1, ‘foresee’: 1, ‘heights’: 1, ‘that’: 1, ‘capable’: 1, ‘reaching.’: 1}
82
(a) What will be the output?
(i) It will display first 20 characters. (ii) It will display 20th character and
onwards.
(iii) It will display first 20 bytes. (iv) It will display content at 20th
byte.
(b) Meenu, Mohan's friend has written the following Python code.
ANSWERS
1 (b) f.read()
2 (c) all lines from the file
(i) Text File (default mode)
3
(ii) File.write(“ABC”)
4 ife y
5
83
6
84
BINARY FILES
Topics Covered :
o Binary file: basic operations on a binary file:
o Open using file open modes (rb, rb+,wb,wb+, ab, ab+),
o Close a binary file,
o import pickle module, dump() and load() method,
o read, write/create, search, append and update operations in a binary file.
Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and displays
in a human-readable format.
There are three basic modes of a binary file:
The plus symbol followed by file mode is used to perform multiple operations together. For
example, rb+ is used for reading the opening file for reading and writing. The cursor position is
at the beginning when + symbol is written with file mode.
Binary File Modes: File mode governs the type of operations read/write/append possible in the
opened file. It refers to how the file will be used once its opened.
File Description
Mode
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is created. If
file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended at the end.
rb+ Read and Write: File should exist, Both read and write operations can be
performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is truncated.
85
Pickle Module: Python pickle is used to serialize and deserialize a python object structure.
Any object on python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into
a byte stream. It is also known as serialization
Example:
import pickle
In this module,we shall discuss two functions of pickle module, which are:
i) dump():To store/write the object data to the file.
ii) load():To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(objname, file-object )
pickle.load(file-object)
OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more record(y/n): y
86
Enter student Roll No: 1202
Enter student Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]
OUTPUT:
Enter the name to be updated Sunil
Enter the updated Roll number 1204
Record updated
87
Delete a record from binary file:
import pickle
def deletestudent():
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
WORKSHEET
LEVEL – 1
I Answer the following questions Marks
4 Raman open a file in readmode, but the file doesn’t exist in the folder. 1
Python raised an error for the code. What type of error will be shown?
88
6 Pickling is otherwise known as ________________ 1
2 The code given below reads from a file “sales.dat” which has following 3
information [itemcode, amount] Read from the file and find the sum of
the amount.
import pickle
F1 = open ("sales.dat", "rb")
sum = 0
while True:
try:
________________
89
________________
except EOFError:
break
print (sum)
F1.close()
91
4.writer.writerow(row): Write the row parameter to the writer’s file
object, formatted according to delimiter defined in writer function.
writerows(rows): Writes multiple rows (sequence) to the writer’s file
object
III 1.Binary files store the information in the form of a stream of bytes
similar to the format a computer memory holds data. Also there is no
delimiter for a line and no translations occur in binary files. Thus binary
files are faster and easier for a program to read and write. So the best
method for a data or program information is to store it as binary files.
1. Program
L = pickle.load(F1)
1. sum = sum + L[1]
IV
1. Mode & Description
a) r - reading only. Sets file pointer at beginning of the file. This is
the default
a. mode.
b) rb – same as r mode but with binary file.
c) r+ - both reading and writing. The file pointer placed at the
a. beginning of the file.
d) rb+ - same as r+ mode but with binary file.
e) w - writing only. Overwrites the file if the file exists. If not,
a. creates a new file for writing.
f) wb – same as w mode but with binary file.
g) w+ - both writing and reading. Overwrites. If no file exists,
a. creates a new file for R & W.
h) wb+ - same as w+ mode but with binary file.
i) a -for appending. Move file pointer at end of the file.Creates
a. new file for writing,if not exist.
j) ab – same as a but with binary file
92
It returns read bytes in the form of a string ending with line character or
returns a blank string if no more bytes are left for reading in the file.
e.g. f1=open(“E:\\mydata\\info.txt”)
info=f1.readlines()
output:
The Dowry system is evil in society
c) readlines() – Read all lines and returns them in a list
output:
[“The Dowry system is evil in society.\n”” It has reduced the sacred affair
of marriage to a business deal.\n”“Brides are treated as a marketable
commodity. \n””The parents of the brides are often put under inhuman
pressure for a handsome dowry.\n“]
3.c,c,c,d,c
LEVEL – 2
Answer the following questions Marks
3 The _________ files are used to store large data such as images, video 1
files, audio files etc
4 ______ module is used to store data into a python objects with their 1
structure.
5 ______ function of pickle module is used to write data into binary 1
6 _______ function of pickle module is used to read data from binary file. 1
7 Ms. Suman is working on a binary file and wants to write data from a 1
list to a binary file. Consider list object as L1, binary file suman_list.dat,
and file object as f. Which of the following can be the correct statement
for her?
a) f = open(‘sum_list’,’wb’); pickle. dump(L1,f)
b) f = open(‘sum_list’,’rb’); L1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(L1,f)
93
d) f = open(‘sum_list’,’rb’); L1=pickle.load(f)
8 Ranjani is working on the sports.dat file but she is confused about how 1
to read data from the binary file. Suggest a suitable line for her to fulfil
her wish.
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________
print(data)
f1.close()
sports_read()
4 The code given below writes Name and Roll Nos into a binary file. Fill 2
in the blanks to complete the code.
import pickle
with open ("file.dat", "wb") as F1:
while True:
op = int (input ("Enter 1 to add data, 0 to quit"))
if (op == 1):
__________________________
__________________________
pickle.dump([name,rollno],F1)
elif op == 0:
break
import pickle
#open file in binary mode for writing.
95
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
a) Fill in the blank in line 1 to open file in binary mode for append
data to the file
b) Fill in the blank in line 2 to pickle the list and write to file
96
4 A file sports.dat contains information in following format [event, 3
participant].
Write a program that would read the contents from file and copy only
those records from sports.dat where the event name is “Athletics” in
new file named Athletics.dat
5 A binary file “STUDENT.DAT” has structure [admission_number, 3
Name, Percentage]. Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of
students scoring above 75%
6 What is pickle.dump()?What is pickle.load()? 3
7 Write a function in to search and display details of all trains, whose 3
destination is "Delhi" from a binary file "'TRAIN .DAT'" Assuming the
binary file is containing the objects of the following dictionary type:
Train = {'Tho' :_______ , 'From': _____, " To': ________}
ANSWERS
I 1.Files
2. Newline (\n)
3. Binary
4. PICKLE
5.dump()
6.load()
7.option d
8.data = f1.load(f).
9. c
10. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
97
E.g.: CSV files – Comma Separated Files
TSV files – Tab separated files
2. Python file object provides methods and attributes to access and
manipulate files. Using file objects, we can read or write any files.
Whenever we open a file to perform any operations on it, Python returns
a file object.
3.The difference between Write() and WriteLine() method is based on
new line character.
Write() method displays the output but do not provide a new line
character.
WriteLine() method displays the output and also provides a new line
character it the end of the string, This would set a new line for the next
output.
4.rollno=int(input("Enter the Roll Number: "))
name=input("Enter the name: ")
5.
import pickle
def writefile():
f=open("datafile.dat", "wb")
list=["Apple","Mango", "Banana"]
pickle.dump(list,f)
f.close
writefile()
print("Writing done")
6. a) ab
b)pickle.dump(employee, outfile)
7. ['Fifth', 'fourth', 'third', 'second"]
III 1. Pickle module provides us the ability to serialise and deserialize objects
that is, it helps to convertobjects into bitstreams that can be stored in
files and later utilised to recreate the original objects.
98
For us, writing different kinds of objects into the binary file and later,
reading the file's content is really challenging.The fact that some of the
objects may have changing lengths makes this a tedious task. So we use
the pickle module to solve this issue since it can handle dictionaries,
sets, lists, tuples, classes, and more.It can store lists, Tuples,
dictionaries, sets, classes etc.
2.
import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)
F1.close()
3.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()
4.
import pickle
99
F1 = open ("sports.dat", "rb")
F2 = open ("athletics.dat", "wb")
sum = 0
while True:
try:
l = pickle.load(F1)
if (l[0].lower() == "athletics"):
print (l)
pickle.dump(l,F2)
except EOFError:
break
F1.close()
F2.close()
5.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
100
6. dump() function is used to store the object data to the file.
dump( object, filehandle )
It takes 3 arguments.
First argument is the object that we want to store.
The second argument is the file object we get by opening the desired
file in write-binary (wb) mode.
the third defines the protocol.
101
print("Not found !!!")
file.close()
search()
LEVEL – 3
Answer the following questions Marks
1. Write Python statements to open a binary file "student.dat" in both read & 1
write mode.
2. Which of the following statement is true? 1
a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
3. Read the following Python code carefully and answers the question given after 1
the code
1
import pickle
#open file in binary mode for writing.
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
Fill in the blank in line 1 to open file in binary mode for append data to the
file.
Fill in the blank in line 2 to pickle the list and write to file
102
myfile = open("test.bin",'wb')
pickle._________ #Statement 1
myfile.close()
103
15. How can you delete a file? Write a pseudocode to delete a file 2
16. Write a function to read name and roll no from a binary file. 3
104
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
____________ #3 statement to readfrom the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
average=Total/Countrec print("average percent of class = ",average)
AddStudents()
GetStudents()
105
II. Which of the following commands is used to write the list L into the
binary file,
STUDENT.DAT? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
III. Which of the following commands is used to read each record from the
binary
file STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
IV. Which of the following statement(s) are correct regarding the file
access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing
file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the
file if it exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the
file exists
106
d. moves the current file position to a given specified position
107
14.
A binary file is a file whose content is in a binary format consisting of a series
of sequential bytes, each of which is eight bits in length.Binary Files contain
raw data so are not in human readable format. It can be read by using some
special tool or program.
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc
15.
To delete a file, import the OS module, and run its os.remove() function.
import os
os.remove("demofile.txt")
16.
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
108
III 1.
I. a)
II. c)
III. a)
IV. a)
V. d)
2.
Text Files Binary Files CSV Files
1 It is capable to It is capable to It is very common
handle textual data. handle large file. format and
platform
independent.
2 It consists of series It consists of data It consists of plain
of lines of a set of with a specific text with a list of
letters, numbers or pattern without data with a
symbols (String) any delimiter. delimiter.
3 Any text editors No specific It can be read
like notepad can be programs can be using text editors
used to read them. used to read them, like notepads and
python provides spreadsheet
functions to read software.
data.
4 Every line ends There is no It terminates a line
with EOL. specific EOL automatically
character. when the delimiter
is not used after
data.
CSV Files
The CSV (Comma Separated Values) is a special text file format in which rows of data are present
and the individual data elements are separated by commas. The CSV format is the most common
import and export format for spreadsheets and databases. The csv files have the extension .csv
Example for data contained in csv file
Raghu,23,100
109
Tisha,45,230
Yatin,67,90
1. Each record is located on a separate line, delimited by a line break (CRLF). For example:
One,two,three CRLF
four,five,six CRLF
2. The last record in the file may or may not have an ending line break. For example:
One,two,three CRLF
four,five,six
3. There maybe an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
Name,Rollno,Marks CRLF Header line
Raghu,1011,56 CRLF
Swara,1012,78 CRLF
4. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
"one","two","three" CRLF
Eight,nine,ten
[Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13 and
C++/Python notation \r or '\r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and C++/Python
notation \n or '\n'.
110
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is represented
by the character combination CRLF i.e. '\r\n' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character is
represented by the character LF only i.e. '\n' in python.
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character is
represented by the character CR only i.e. '\r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter, newline='\r\n' in
the open() method to avoid adding an extra blank line while processing/displaying output on the
screen ]
In CSV files there can be delimiters other than comma(,)
Tab separated values
Raghu 23 100
Tisha 45 230
Yatin 67 90
Raghu ;23;100
Tisha;45;230
Yatin;67;90
import csv as c
or
import csv
writerow() Vs writerows()
writerow() is used to write a single row to a csv file.
112
writerows() is used to write multiple rows/lines to csv file
To demonstrate writerow() and writerows()
import csv
f=open("one.csv","w",newline='')
csvwriter=csv.writer(f,delimiter=',')
csvwriter.writerow(['one','two','three'])
l=[(23,45,67),(34,56,78),(45,67,78)]
csvwriter.writerows(l)
f.close()
OUTPUT:
one,two,three
23,45,67
34,56,78
45,67,78
WORKSHEET
LEVEL – 1
I Questions (1 mark)
1 CSV files are opened with __________argument to supress EOL translation.
2 The _________ parameter of csv.reader() function is used to set a specific delimiter like a single
quote or double quote or space or any other character.
3 When you read csv file using csv.reader() function it returns the values in _______ object.
4 If you want to change a default delimiter of csv file, you can specify ________ parameter.
5 Which of the following is not a function of csv module?
a. readline()
b. writerow()
c. reader()
d. writer()
6 Anshuman wants to separate the values by a $ sign. Suggest to him a pair of function and
parameter to use it.
A open,quotechar
B writer,quotechar
C open,delimiter
D writer, delimiter
7 Which of the following is tasks cannot be done or difficult with CSV module?
A Data in tabular form
B Uniqueness of data
C Saving data permanently
D All of these
8 Observe the following code and fill the blank in statement1
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
113
print(_____) #statement4
a) open(“data.csv”)
b) f=open(“data.csv”)
c) Both A & B are Correct
d) Both A & B are incorrect
9 A CSV file is also known as a ….
A. Flat File
B. 3D File
C. String File
D. Random File
10 The command used to skip a row in a CSV file is
A. next()
B. skip()
C. omit()
D. bounce()
11 Which of the following is a string used to terminate lines produced by writer()method of csv
module?
A. Line Terminator
B. Enter key
C. Form feed
D. Data Terminator
12 Making some changes in the data of the existing file or adding more data is called
A. Editing
B. Appending
C. Modification
D. Alteration
13 Observe the following code and fill the blank in statement4
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4
a) r
b) row
c) f
d) csv
14 One row of CSV file can be considered as _______ in terms of database
15 What is the output of the following program?
import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d: print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
114
mumbai,andheri
A. chennai,mylapore
B. mumbai,andheri
C. Chennai, mumbai
D. chennai,mylapore
mumbai, andheri
II Questions (2 marks)
1 What is the difference between writer object’s writerow() and writerows() function?
2 How will you sort more than one column from a csv file?Give an example statement.
3 What Is CSV File”
4 Syntax for opening Student.csv file in write mode is
myfile = open("Student.csv","w",newline='').
What is the importance of newline=''?
5 What is the output of the following program if the student.csv file contains following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row)
III Questions (3 marks)
1 Write a note on open() function of python. What is the difference between the two methods?
2 Write a Python program to modify an existing file
3 Write a Python program to read a CSV file with default delimiter comma (,).
4 What is the difference between reader() and DictReader() function?
5 Observe the following code and fill in the given blanks:
import csv
with _________ as f: #1
r = csv.______(f) #2
for row in ______: #3
print(_____) #4
IV Questions (5 marks)
1 Vijay Kumar 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.
115
#csv file reading code
def readRecord(): # to read data from CSV file
f=open('users.csv','r')
creader = csv._________(f) # Line 3
for row in creader:
print (row[0],row[1])
__________ # Line 4
addRecord("Neil", "123@456")
addRecord("Swati","sw@tee")
addRecord("Farida","myname@FRD")
readRecord() #Line 5
1a Name the module he should import in Line 1.
1b In which mode, Vijay should open the file to append data into the file.
1c Fill in the blank in Line 3 to read the data from a csv file.
1d Fill in the blank in Line 4 to close the file
1e Write the output he will obtain while executing Line 5.
def writeFile(Gift_code,Gift_name):
F=open(“gift.csv”,‟___‟) #Line 2
FW=csv.________(F) #Line 3
FW.writerow([Gift_code,Gift_name)
F.close()
writeFile(101,”Photoframe”)
writeFile(102,”Soft Toys”)
writeFile(103,”Flower Pot”)
readFile() #Line 5
3a Name the module she should import in line 1.
3b In which mode Puneeta should open the file to add data in it?
3c Fill in the blanks in Line 3 to write data to csv file gift.csv
3d Fill in the blank in Line 4 to open the csv file from the disk
3e Which user defined function is used here for reading data?
4 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he
116
has been assigned an incomplete python code (shown below) to create a CSV File
'Student.csv' (content shown below). Help him in completing the code which creates the
desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
I.Identify the suitable code for blank space in line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) Csv
II.Identify the missing code for blank space in line marked as Statement-2?
a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"
III.Choose the function name (with argument) that should be used in the blankspace of line
marked as Statement-3
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
IV.Identify the suitable code for blank space in line marked as Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,sectionc) co.connect()
117
V.Choose the function name that should be used in the blank space of line markedas Statement-
5 to create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
LEVEL – 2
I Answer the following Marks
1 The expansion of CRLF is 1
(A) Control Return and Line Feed
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed
ans (D) Carriage Return and Line Feed
2 Importing CSV files can be much faster, and it also consumes less memory 1
while comparing with .xls files(True/False)
an True
3 A ________ parameter is used to quote all fields of csv files.
ans Quoting
4 Read following statement about features of CSV file and select which
statement is TRUE?
118
5 Which of the following file types can be opened with notepad as well as
ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of thes
ans CSV Files
6 What is the output of the following program if the student.csv file contains 1
following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
ans Akshaj, 400
II Answer the following Marks
1 Write a program to copy the data from “data.csv” to “temp.csv” 2
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( )
119
2 When is a CSV file ? When do we use CSV? 2
A CSV (Comma Separated Values) file is a form of plain text document
which uses a particular format to organize tabular information. CSV file
format is a bounded text document that uses a comma to distinguish the
values. Every row in the document is a data log. Each log is composed of
one or more fields, divided by commas. It is the most popular file format
for importing and exporting spreadsheets and databases.
3 Write a Python program to modify an existing file.
ans import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines [3] = row
with open( student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
120
90,Executive,100,1700
b
It tells you the current position of cursor within the file
Syntax: file_object.tell()
2 What is difference between tell() and seek() methods? 3
ans tell() seek()
It returns the current position of Change the cursor position by
cursor in file. bytes as specified by the offset
Example: Example:
fout=open(“story.txt”,”w”) fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”) fout.write(“Welcome Python”)
print(fout.tell( )) fout.seek(5)
fout.close( ) print(fout.tell( ))
fout.close( )
Output : 4 Output : 5
IV Answer the following Marks
1 Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” 5
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 the CSV
file
f=open(' user.csv','________') # Line 2
121
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._________(newFile) # 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
122
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)
file.close()
a. In which mode should Ronit open the file to make a new file?
b. Which Python keyword should be used to manage the file stream?
c. Fill in the blank in Line 3 to read the data from a csv file.
d. Fill in the blank to write name into marks.csv
e. Fill in the blank to write class into marks.csv.
ans import csv
file = open('class.csv', 'w', newline="");
writer = csv.writer(file)
file.close()
123
CSV Module’s Reader Function:
(i) We can read the contents of CSV file with the help of csv.reader()
method. The reader function is designed to take each line of the file and
make a list of all columns.
(ii) Then, choose the column we want the variable data for. Using this
method one can read data from csv files of different formats like quotes
(""), pipe (|) and comma (,).
The syntax for csv.readerf() is
csv.reader(fileobject,delimiter,fmtparams) where
(iii) file object : passes the path and the mode of the file
(iv) delimiter:an optional parameter containing the standard dilects like , |
etc can be omitted.
(v) fmtparams : optional parameter which help to override the default
values of the dialects like skipinitialspace,quoting etc. can be omitted.
CSV file with default delimiter comma (,): The following program read a
file called “sample 1. csv” with default delimiter comma (,) and print row
by row.
Program:
124
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open('c:\\pyprg\\samplel.csv', 'r') as F:
#other way to open the file is f= ('c:\\pyprg\\sample1.csv', 'r')
reader = csv.reader(F)
# printing each line of the Data row by row print(row)
F.close()
Output:
(i) To read a CSV file into a dictionary can be done by using DictReader
class of csv module which works similar to the reader() class but creates an
object which maps data to a dictionary.
(ii) The keys are given by the fieldnames as parameter. DictReader works
by reading the first line of the CSV and using each comma separated value
in this line as a dictionary key.
(iii) The columns in each subsequent row then behave like dictionary
values and can be accessed with the appropriate key (i.e. fieldname).
125
(iv) If the first row of your CSV does not contain your column names, you
can pass a fieldnames parameter into the DictReader s constructor to assign
the dictionary keys manually.
(v) The main difference between the csv. reader() and DictReader() is in
simple terms csv.reader and csv.writer work with list/tuple, while
csv.DictReader and csv. DictWriter work with dictionary, csv. DictReader
and csv. DictWriter take additional argument fieldnames that are used as
dictionary keys.
Program:
import csv
filename = c:\\pyprg\\sample8.csv’
input_file =csv.DictReader(open(filename,’r’))
for row in input_file:
print(dict(row) ) #dict() to print data
Output:
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’ ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}
127
CSVOpen()
CSVRead()
You as an expert of Python have to provide the missing statements and
other related queries based on the following code of Radha.
Answer any four questions (out of five) from the below mentioned
questions.
4.1 Choose the appropriate mode in which the file is to be opened in append
mode
(Statement 1)
a. w+
b. ab
c. r+
d. a
Correct Answer: d. a
ans
4.2 Which statement will be used to create a csv writer object in Statement 2.
a. csv.writer(csvf)
b. csv.writer(csvf)
c. csvf.writer()
d. cs.writer(csvf)
128
ans Correct Answer: b. cw.writerow(['Title','Author','Price'])
4.4 Which statement will be used to read a csv file in Statement 4.
a. cs.read(csvf)
b. csv.reader(csvf)
c. csvf.read()
d. csvf.reader(cs)
(A) py
(B) xls
(C) csv
(D) os
129
Ans (C) csv
2 To open a file c:\scores.csv for reading, we use _______ command. 1
a) infile = open(“c:\scores.csv”, “r”)
b) infile = open(“c:\\scores.csv”, “r”)
c) infile = open(file = “c:\scores.csv”, “r”)
d) infile = open(file = “c:\\scores.csv”, “r”)
Ans infile = open(“c:\\scores.csv”, “r”)
3 To read the entire content of the CSV file as a nested list from a file object 1
infile, we use __________ command.
(a) infile.read()
(b) infile.reader()
(c) csv.reader(infile)
(d) infile.readlines()
Ans c) csv.reader(infile)
4 The CSV files are popular because they are 1
130
written the following code. As a programmer, help him to successfully
execute the given task.
import______ # Line 1
131
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
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)
2 What is the difference between writer object’s writerow() and writerows() 5
function? Write a python code based on these function
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 = ‘,’)
132