File Handling
File Handling
1- Opening a file.
2- Performing operations (read, write) or processing data.
3- Closing the file.
Text file: A text file is simply a sequence of ASCII or Unicode characters. A line is a
sequence of characters, stored on permanent storage. In a text file, each line is
terminated by a special character, known as End of Line (EOL). Text file can be
created using any text editor. Ex. Myfile.txt.
Binary file: A binary file stores the data in the same way as stored 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.
CSV file: CSV (Comma Separated Values) is a simple text file format for storing data
in tabular form such as spread sheet or database. The data is organized with one record
on each line and each field is separated by comma.
3 Any text editors like No specific programs can be It can be read using text
notepad can be used to used to read them, python editors like notepads and
read them. provides functions to read spreadsheet software.
data.
4 Every line ends with There is no specific EOL It terminates
EOL. character. a
line automatically
when the
delimiter is not used after
data.
Absolute Path – It is a full path of the file from the root directory. Absolute paths ensure
that Python can find the exact file on your computer.
Ex : - C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt f=open(“C:\\Users\\Tanmay\\
Desktop\\Delete\\file_handling.txt”,r)
Relative Path – It is the path of the file from the current working directory.
Relative Path is the hierarchical path that locates a file or folder on a file system
starting from the current directory. The relative path is different from the absolute path,
which locates the file or folder starting from the root of the file system.
f=open(“file_handling.txt”,r)
Operation On Files
In Python
We use open () function in Python to open a file in read or write mode. open ( ) will
return a file object. To return a file object we use open() function along with two
arguments, that accepts file name and the mode, whether to read or write. So, the
syntax being: open(filename, mode). There are three kinds of mode, that Python
provides and how files can be opened:
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
Modes Description
1. r - Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode. Gives error if file does not exist.
2. r+ - Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
3. w - Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
4. w+ - Opens a file for both writing and reading. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and writing.
5. a - Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
6. a+ - Opens a file for both appending and reading. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads
the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string. For specified n, reads
at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them list in which each line as a string element.
File_object.readlines()
write() function
The write() function will write the content in the file without adding any extra characters.
file_name.write(content)
writelines() function98
This function writes the content of a list to a file. file_name.
writelines(list_of_lines)
# Program to show various ways to read data from a file.
# Creating a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
Output:
Output of Readline(9)
function is
Hello
If we want to access data in a random fashion, then Python gives us seek() and tell()
functions to do so
This function returns an integer that specifies the current position of the file object in
the file. The position so specified is the byte position from the beginning of the file till
the current position of the file object. The syntax of using tell() is: A=file_object.tell()
This method is used to position the file object at a particular position in a file. The
syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be
moved. reference_point indicates the starting position of the file object. That is, with
reference to which position, the offset has to be counted. It can have any of the
following values:
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning
of the file.
For example, the statement fileObject.seek(5,0) will position the file object at 5th byte
position from the beginning of the file.
SAMPLE PROGRAMS
2.Write read contents from story.txt and count no: of independent words “to”
in the file
Ans: string
PRACTICE QUESTIONS
1. Write a program to read contents from the text file story.txt and count no:of vowels
in it
2. Write a program to read contents from the text file myfile.txt and find average word
count
3. Write a program to read contents from the text file library.txt and count “is” as
independent word
4. Write a program to read contents from the text file diary.txt and count number of
lines with Starting letter “T” or “M”
5. Write a program to read contents from the text file mydiary.txt and count number of
lines with ending letter “r”
3. To read the entire remaining contents of the file as a string from a file object myfile,
we use
a. myfile.read(2)
b. myfile.read()
c. myfile.readline()
d. myfile.readlines()
4. A text file is opened using the statement f = open(‘story.txt’). The file has a
total of 10 lines. Which of the following options will be true if statement 1 and
statement 2 are executed in order.
Statement 1: L1 = f.readline( )
Statement 2: L2 = f.readlines( )
a. L1 will be a list with one element and L2 will be list with 9 elements.
b. L1 will be a string and L2 will be a list with 10 elements.
c. L1 will be a string and L2 will be a list with 9 elements.
d. L1 will be a list with 10 elements and L2 will be an empty list.
5. Which function of a file object can be used to fetch the current cursor position
in terms of number of bytes from beginning of file? a. seek( )
b. bytes( )
c. tell( )
d. fetch( )
a. 33
b. 31
c. 28
d. 3
fin =
open('fracture.txt’)
data = fin.read(10)
print(data[0:3], end=
‘’) data =
fin.readline(5)
print(data[0:3] ,
end= ‘’) fin.seek(0)
data = fin.read(4)
print(data[0:3] ,
end= ‘’)
a. AllngsAll
b. AllcanAll
c. Allcancan
d. Allngscan
8. What will be the most correct option for possible output of the following code,
given that the code executes without any error.
f = open(‘cricket.txt’)
data = f.read(150)
print(len(data))
9. For the following python code, what will be the datatype of variables x, y, z given
that the code runs without any error?
f=
open(‘story.txt’
) x = f.read(1) y
= f.readline() z
= f.readlines()
a. string, list, list
b. None, list, list
c. string, string, list
d. string, string, string
How much can you lose, How much can you win
fin =
open('fracture.txt’) x
= 0 for line in fin:
words = line.split( )
for w in words:
if len(w)>x:
x = len(w) print(x)
a. 12
b. 11
c. 13
d. 10
Answers:
1. a. Beginning of file
2. d. All of the mentioned
3. b. myfile.read()
4. c. L1 will be a string and L2 will be a list with 9 elements.
5. c. tell( )
6. d. 3
7. a. AllngsAll
8. d. Less than or equal to 150
9. c. string, string, list
10. a. 12
b) File.write(“ABC”)
Ans: A named entity, usually stored on a hard drive that contains a stream of characters
are called files.
2. Write a function in Python that counts the number of “the” or “this” words
present in a text file “myfile.txt”.
Example: If the “myfile.txt” contents are as follows:
This is my first class on Computer Science. File handling is the easiest topic for
me and Computer Networking is the most interesting one.
The output of the function should be: Count of the/this in file: 3
Answer:
def displayTheThis():
num=0
f=open("myfile.txt","r")
N=f.read()
M=N.split() for x in
M: if x=="the" or
x== "this":
print(x)
num=num+1 f.close()
print("Count of the/this in
file:",num)
4. Write a Python program to count all the line having 'a' as last character.
Answer:
count =0
f=open('fracture.txt',"
r") data=f.readlines()
for line in data:
if line[-2] == 'a': count=count+1 print("Number of lines
having 'a' as last character is/are : " ,count) f.close()
5. Assume that a text file named TEXT1.TXT already contains some text written
into it, write a program with a function named vowelwords(),that reads the file
TEXT1.TXT and create a new file named TEXT2.TXT ,which shall contain only
those words from the file TEXT1.TXT which don’t start with an uppercase vowel(i.e.
with ‘A’,’E’,’I’,’O’,’U’) , for example if the file TEXT1.TXT contains Carry
Umbrella and Overcoat When it Rains then the file TEXT2.TXT shall contain Carry
and when it Rains.
Answer:
file1=open('TEXT1.txt','
r')
file2=open('TEXT2.txt','
w') text = file1.read()
text=text.split()
vowels=['A','E','I','O','U']
for i in text:
file2.write(i)
file2.write(" ")
file1.close()
file2.close()
vowelwords()
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC
YEAR 2022-23 74
BINARY FILES
File
Operations
Read
operations in
Binary file a binary file Modulesand
Methods
Basic write/create
operat io import pickle
module
● Binary file(used to store binary data such as images, video files, audio files etc.) is a non-text
file. It contains data as 1s and 0s(computer readable format).
● Binary files are faster in processing and consumes less memory compared to text files.
● Extension of binary files are any non-text file exensions like .bin,.dat etc
● File opening mode must attach ‘b’ to it for operating binary file(Ex: ‘rb’- for reading)
Operations on binary file
• Writing data into binary file
• Searching of data
• Modifying data
• Deleting data
• Appending data
pickle.load() can generate runtime exceptions like EOFError. try and except block will
handle runtime errors raised due to EOF (end of file) .In try block write all the
statements that can generate an exception and in except block write code to handle the
exception.
Write a program to write contents to a binary file stud.dat with record format
[rollno,name,marks]
Write a program to read contents from the file stud.dat and display those records
whose marks >90. Assume stud.dat existing in the system with the record format
[rollno,name,marks]
Write a program to update records in the file stud.dat with records in the format
[rollno,name,marks].Increase 10 marks to the student whose rollnumber entered by
the user
Appending data in to a binary file
Write a program to append records into the file stud.dat with records in the format
[rollno,name,marks]
The with statement is a compact statement which combines the opening of file ,
processing of file along with inbuilt exception handling.The with statement will also
close the file automatically after with block is over.
content = myObject.read()
Here, we don’t have to close the file explicitly using close() statement. Python will
automatically close the file.
SAMPLE QUESTIONS
1. A binary file “employees.dat” has structure [empid, empname, age, department]
PRACTICE QUESTIONS
(i) Write a user defined function MakeFile( ) to input data for a record and add
to Book.dat.
i)Write a user defined function CreatePC() to input data for a record and append in
Computers.dat .
ii. Write a function FindPCs(Price) in Python which accepts the Price as parameter
and display only those computer records from Computers.dat which are having less
than or equal to given price.
f.close()
3. Which is the valid syntax to write an object onto a binary file opened in the write
mode?
a. pickle.dump(<object to be written>, <file handle of open file>)
b. pickle.dump(<file handle of open file>, <object to be written>)
c. dump.pickle(<object>, <file handle>)
d. None of the above
4. What is the binary file mode associated with “ file must exist, otherwise error will
be raised and reading and writing can take place”.
a. wb+
b. w+
c. rb
d. rb+
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4
6. A binary file “salary.dat” has structure [employee id, employee name, salary].
What the following code will display: def records():
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() records()
7. In which file, no delimiters are used for line and no translations occur?
(a) Text file
(b) Binary file
(c) csv file
(d) None of the above
8. Choose the file mode used to write data into binary file.
(a) rb
(b) wb
(c) r+
(d) w+
9. Which of the following function is used to read data from a binary file?
(a) write
(b) load
(c) dump
(d) scan
10. Dima is trying to read a list l1 from a binary file ‘num’. Consider the
following code written by her.
print(l1)
f1.close()
(a) pickle.load(f1)
(b) pickle.load(l1,f1)
(c) pickle.read(f1)
(d) pickle.dump(l1,f1)
Answers:
d.Display the details of those employees whose salary is less than 20000.
(b) Binary file
(b) wb
(b) load
(a) pickle.load(f1)
CASE STUDY QUESTIONS
Amit Kumar of class 12 is writing a program to store roman numbers and find their
equivalents using a dictionary. He has written the following code. As a programmer,
help him to successfully execute the given task.
(a) pickle
(b) wb
(c) rb
(d) file2.close()
(e) C
I.Write a user defined function CreateEmp() to input data for a record and add to emp.dat.
II.Write a function display() in Python to display the detail of all employees.
Answer:
I.
import pickle
def
CreateEmp():
f1=open("emp.dat",'wb')
eid=input("Enter E. Id")
ename=input("Enter
Name")
designation=input("Enter
Designation")
salary=int(input("Enter Salary"))
l=[eid,ename,designation,salary]
pickle.dump(l,f1) f1.close()
II.
import
pickle def
display():
f2=open("emp.dat","rb"
) while True:
try:
rec=pickle.load(f2)
print(rec['eid'],rec['ename'],rec['designation'],rec['salary'])
except EOFError: break f2.close()
I)
import
pickle def
createemp():
f1=open("emp.dat",'ab')
eid=input("Enter E. Id")
ename=input("Enter Name")
designation=input("Enter
Designation")
salary=int(input("Enter Salary"))
l=[eid,ename,designation,salary]
pickle.dump(l,f1) f1.close()
f2=open("emp.dat","rb
") while True:
try:
rec=pickle.load(f2) if
(rec['designation']=='Manager'):
print(rec['eid'],rec['ename'],
rec['designation'],rec['salary'])
except EOFError: break
f2.close()
CSV FILE
• A Comma Separated Values (CSV) file is a plain text file that contains the commaseparated
data.
• These files are often used for exchanging data between different applications.
• CSV files are usually created by programs that handle huge amounts of data. They are used to
export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle, MySQL). It can be used
to import data into a spreadsheet or a database.
• writer( ) reader( )
Both the methods return an Object of writer or reader class. Writer Object again have two
methods – writerow( ) , writerows( ).
writer( ) Methods
This function returns a writer object which is used for converting the data given by the
user into delimited strings on the file object. writer( ) Object Methods –
Example:-
## writerow()
import csv
row=['Nikhil', 'CEO', '2',
'9.0']
f=open("myfile.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
## writerows()
import csv
rows = [['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','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)
for i in r_obj:
print(i)
import csv
f=open("myfile.csv
",'r') r_obj =
csv.reader(f) for
data in r_obj:
print(data)
f.close()
SAMPLE QUESTIONS:
4. _____ module of Python provides the functionality to read and write tabular data in
CSV file.
a. pickle
b. csv
c. file
d. ccv
11. The _______argument of open function is to specify how Python handle the
newline characters in csv file
a. newline
b. line
c. mode
d. char
13. To specify a different delimiter while writing into a csv file, argument is used with
writer object :
a. newline
b. separator
c. character
d. delimiter
14. Which mode opens the file for exclusive creation, which fails in the case where file
already exists
a. a
b. w
c. x
d. r
15. The file mode to open a CSV file for reading as well as writing is .
a. a+
b. w+
c. r+
d. All the above.
16. Identify the line number which may cause an error:
import csv #Line1 line=[[1,2,3],[4,5,6]]#Line 2
with open("sample.csv","w",newline="") as csvfile:
#Line3 writer=csv.writer(csvfile,delimiter="|")
#Line4 for line in writer: #Line5
writer.writerow(line)
a. Line1
b. Line2
c. Line 4
d. Line
19. Which of the following parameter needs to be added with open function to avoid blank
row followed by each record in the CSV file?
a. quotechar
b. quoting
c. newline
d. skiprow
20. Ajaikrishna wants to separate the values by a $ sign. Suggests him a pair of
function and parameter to use it. a. open, quotechar
b. writer, quotechar
c. open, delimiter
d. writer, delimiter
21. Tejalakshmi of Class 12 have written the below code . Observe and fill in the given
blanks so that it opens the file “data.csv” and read and print all the records.
I. What must be filled in line 1?
a. Open(“data.csv”,”r”)
b. open(“data.csv”)
c. “data.csv”
d. File
V. What is the default data type of data read from this file?
a. List
b. String
c. Tuple
d. Integer
22. Sudev, a student of class 12th, is learning CSV File Module in Python. During
examination, he has been assigned an incomplete python code to create a CSV file
‘customer.csv’ .Help him in completing the code which creates the desired CSV file.
I. Identify suitable code for the blank space in line marked as Statement-
1. a) include
b) add
c) Import
d) import
II. Identify the missing code for the blank space in line marked as Statement-
2. a) Customer
b) reader
c) csvwriter
d) writer
III. Identify the argument name for the blank space in line marked as Statement-3?
a) Row
b) Rec
c) row
d) rec
IV. Identify the missing file name for the blank space in line marked as Statement-
4? a) customer
b) customer.csv
c) customer.txt
d) customer.dat
V .Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec
23. Daya of class 12 is writing a program to create a CSV file “empdata.csv” with
empid, name & mobile number. Also to search a particular empid and display its
record details. He has written the following code. As a programmer, help him to
successfully execute the given task.
Choose the module he should import in Line 1.
a) math
b) pickle
c) csv
d) random
II. Choose a code to write the column heading from fields list in
Line2. a) writerows(fields)
b) writerow(field)
c) writerow(fields)
d) writerows(fields)
IV. Choose a code for line 4 to read the data from a csv
file. a) csv.reader(f)
b) csv.read(f) d) pickle.load(f) e) f.read()
V. Choose the correct variable (list value) to check “emplid” in Line5
a) Row[0]
b) Rec[0]
c) row[0]
d) rec[0]
II. Choose the file mode to be passed to add new records in Statement-2.
a) w
b) r
c) w+
d) a
III. Identify the correct variables in Statement-3 to store data to the file.
a) country,capital
b) Country,Capital
c) Coun,Cap
d) [Country,Capital]
IV. Choose the correct option for Statement-4 to read the data from a csv file.
a) Reader()
b) reader()
c) read
d) reader
25. Rinsha of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. She has written the following code.
As a programmer, help her to successfully execute the given task.
I. Name the module she should import in Line 1.
a. CSV
b. csv
c. math
d. File
II. In which mode, Rinsha should open the file to add data into the file.
a. r
b. a
c. w
d. w+
III. Fill in the blank in Line 3 to read the data from a csv file.
a. writer()
b. reader()
c. write()
d. read()
IV. Fill in the blank in Line 4 to close the file.
a. End()
b. Close()
c. close()
d. end()
26. Consider the following csv file and the code fragment associated with the following
csv file :
II. What will be the output printed by the above code if the break is replaced with continue?
a. SLNO12345
b. SLNO
c. The entire content
d. Error
III. What will occur if the file stud.csv is not existing in the mentioned
path? a. It will create a new one
b. It will create an error
c. None of the above
d. It will cause a system reboot
IV. Which statement in the above code will help to move to the next
record? a. fobj.next()
b. next(fobj)
c. fobj.move()
d. fobj.forward()
27. Sai Krishna has created the following csv file named item.csv:
He has written the following program for managing the file. Help him to find the
answers for the following questions.
ANSWERS