Chapter 5 File Handling
Chapter 5 File Handling
File Handling
Type A: Short Answer Questions/Conceptual Questions
Question 1
Answer
The "w" mode in file opening is The "a" mode in file opening is used for
used for writing data to a file. appending data to a file.
If the file exists, Python will If the file exists, the data in the file is retained
truncate existing data and over- and new data being written will be appended to
write in the file. the end of the file.
Question 2
Answer
File objects are used to read and write data to a file on disk. The file object is
used to obtain a reference to the file on disk and open it for a number of
different tasks. File object is very important and useful tool as through a file
object only, a Python program can work with files stored on hardware. All the
functions that we perform on a data file are performed through file objects.
Question 3
Answer
The open() function is used to open a file. The close() function is used to close a
open() function close() function
file object.
It creates a file object, which allows to When we're done working with a file, we
perform various operations on the file, such should always close it using the close()
as reading from it, writing to it, or function to free up system resources
appending data to it. and prevent data loss.
Question 4
Answer
The two different formats of specifying file path for opening the file C:\
Myfiles\Text1.txt in read and write mode are:
Question 5
1. csv
2. binary
3. math
4. pickle
Answer
pickle
Question 6
Which of the following function is used with the csv module in Python to read
the contents of a csv file into an object ?
1. readrow()
2. readrows()
3. reader()
4. load()
Answer
reader()
Reason — In the CSV module in Python, the reader() function is used to read
the contents of a CSV file into an object. This function returns a reader object
which can be used to iterate over the rows of the CSV file, where each row is
represented as a list of strings. This allows to process the data contained
within the CSV file.
Question 7
When a file is opened for output in write mode, what happens when
Answer
When a file is opened for output in write mode ("w" mode) in Python, the
behaviour differs depending on whether the mentioned file already exists or
not:
(i) If the mentioned file does not exist — If the file specified in the open()
function does not exist, Python will create a new file with the given name.
The file will be opened for writing, and any data written to it will be written
from the beginning of the file.
(ii) If the mentioned file does exist — If the file specified in the open()
function already exists, Python will truncate existing data and over-write in
the file. It's essential to be cautious when opening existing files in write
mode, as any existing data will be lost when the file is opened in "w" mode.
Question 8
What role is played by file modes in file operations ? Describe the various file
mode constants and their meanings.
Answer
File modes play a crucial role in file operations in Python as they determine
how the file will be opened and what operations can be performed on it. Each
file mode specifies whether the file should be opened for reading, writing,
appending, or a combination of these operations. Additionally, file modes can
distinguish between text mode and binary mode, which affects how the file
data is handled.
Here are the various text file mode constants in Python and their meanings:
1. "r" — Opens the file for reading only. This is the default mode if no
mode is specified.
3. "a" — Opens the file for writing, but appends new data to the end of
the file.
Here are the various binary file mode constants in Python and their
meanings:
"rb", "wb", "ab", "rb+", "wb+", "ab+" — These modes are similar to their
corresponding text modes ("r", "w", "a", "r+", "w+", "a+"), but they operate
in binary mode.
Question 9
Answer
2. Speed — Reading and writing binary data can be faster than text-
based formats because there is no need for encoding or decoding
operations.
2. Simplicity — CSV files are easy to create, parse, and manipulate using
spreadsheet software.
3. Flexibility — CSV files can store a wide range of data types, including
numbers, strings, and dates.
When do you think text files should be preferred over binary files ?
Answer
Text files should be preferred over binary files when dealing with human-
readable data that does not require special encoding or formatting. They are
ideal for storing plain text, such as configuration files, logs, or documents, as
they are easily editable and can be viewed using a simple text editor. Text
files are also more portable and platform-independent, making them suitable
for data interchange between different systems.
Question 11
Answer
Question 12
When a file is opened for output in append mode, what happens when
Answer
When a file is opened for output in append mode ("a" mode) in Python, the
behaviour differs depending on whether the mentioned file already exists or
not:
(i) If the mentioned file does not exist — If the file specified in the open()
function does not exist, Python will create a new file with the given name.
The file will be opened for writing, and any data written to it will be
appended to the end of the file.
(ii) If the mentioned file does exist — If the file specified in the open()
function already exists, the data in the file is retained and new data being
written will be appended to the end of the file.
Question 13
How many file objects would you need to create to manage the following
situations ? Explain.
Answer
For example :
f = open("file1.txt", "r")
f.close()
f = open("file2.txt", "r")
f.close()
f = open("file3.txt", "r")
f.close()
Here, we are reusing the f file object three times sequentially. We start by
opening file1 in read mode and store its file handle in file object f. We
process file1 and close it. After that, same file object f is again reused to
open file 2 in read mode and process it. Similarly, for file3 also we reuse the
same file object f.
(ii) To merge two sorted files into a third file — In this scenario, where we
need to merge two sorted files into a third file, we would need three file
objects, one for each input file and one for the output file. We would open
each input file for reading and the output file for writing. Then, we would
read data from the input files, compare the data, and write the merged data
to the output file. Finally, we would close all three files after the merging
operation is complete.
For example :
f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
f3 = open("merged.txt", "w")
# Process lines
# Write line to f3
f1.close()
f2.close()
f3.close()
Question 14
Answer
The similarities :
The differences :
1. CSV files have a structured format where data is organized into rows
and columns, separated by delimiters such as commas, tabs, or
semicolons. Text files, on the other hand, can have any structure, and
data may not be organized into rows and columns.
2. CSV files are specifically designed for storing tabular data, such as
spreadsheets, where each row represents a record and each column
represents a field. Text files can contain any type of textual
information.
Question 15
Answer
Question 16
Answer
CSV (Comma-Separated Values) files are popular for data storage due to the
following reasons:
1. Easier to create.
Question 17
How do you change the delimiter of a csv file while writing into it ?
Answer
To change the delimiter of a CSV file while writing into it, we can specify the
desired delimiter when creating the CSV writer object. In Python, we can
achieve this using the csv.writer() function from the csv module. By default,
the delimiter is a comma (,), but we can change it to any other character,
such as a tab (\t), semicolon (;), or pipe (|).
import csv
In this example:
1. We open the CSV file for writing using the open() function with mode
'w'.
3. We then use the writerow() method of the CSV writer object to write
rows to the CSV file, with each row separated by the specified
delimiter.
Question 18
When and why should you suppress the EOL translation in csv file handling ?
Answer
Question 19
If you rename a text file's extension as .csv, will it become a csv file ?
Why/why not ?
Answer
3. File Encoding — CSV files are often encoded using standard text
encodings such as UTF-8 or ASCII.
Question 20
Differentiate between "w" and "r" file modes used in Python while opening a
data file. Illustrate the difference using suitable examples.
Answer
The "w" mode is used to open a file for The "r" mode is used to open a file for
writing. reading.
It creates a new file if the file does not If the file does not exist, it raises a
exist. FileNotFoundError.
"w" mode "r" mode
If the file exists, Python will truncate If the file exists, Python will open it for
existing data and over-write in the file. reading and allow to access its contents.
Example:
Example:
with open("example.txt", "r") as file:
with open("example.txt", "w") as file:
data = file.read()
file.write("Hello, world!\n")
print(data)
Question 21
Answer
(i) f = open('diary.txt', 'r') — This line opens the file diary.txt in read mode
('r'). If the file does not exist, Python will raise an error. If the file exists, the
data will not be erased.
(ii) f = open('diary.txt', 'w') — This line opens the file diary.txt in write mode
('w'). If the file does not exist, Python creates new file with the specified
name. If the file exists, Python will truncate existing data and over-write in
the file.
Question 1
(a)
my_file.read()
(b)
my_file.read(100)
Answer
The provided code snippets (a) and (b) are similar in that they both open the
file poem.txt in read mode ('r'). However, they differ in how they read the
contents of the file:
(a) my_file.read(): This code reads the entire content of the file poem.txt into
a single string. It reads until the end of the file (EOF) is reached.
(b) my_file.read(100): This code reads the first 100 characters from the
file poem.txt into a string. It reads up to the 100 number of characters or
until EOF is reached, whichever comes first.
Question 2
Then what outputs will be produced by both the code fragments given in
question1.
Answer
(a)
my_file.read()
Output
Explanation
This code reads the entire content of the file poemBTH.txt into a single
string. Since no specific number of characters is specified, it will read until
the end of the file (EOF) is reached.
(b)
my_file.read(100)
Output
Explanation
This code reads the first 100 characters from the file "poemBTH.txt" into a
string. It is important to note that the newline at the end of each line will also
be counted as a character.
Question 3
Consider the file poemBTH.txt given above (in previous question). What
output will be produced by following code fragment ?
s1 = obj1.readline()
s2.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
Answer
The code will result in an error because at line 3 there is a syntax error. The
correct syntax is s2 = obj1.readline().
Explanation
s1 = obj1.readline()
s2 = obj1.readline()
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
Output
-frozen boundaries.
2. s1 = obj1.readline() — This line reads the first line from the file obj1
and assigns it to the variable s1.
3. s2 = obj1.readline() — This line reads the next line from the file obj1,
starting from the position where the file pointer currently is, which is
the beginning of the second line (from the previous readline() call).
Then assigns it to the variable s2.
Question 4
Write code to open file contacts.txt with shown information and print it in
following form :
Answer
Kumar 8574075846
Priya 5873472904
Neetu 7897656378
Output
Question 5
Consider the file "poemBTH.txt" and predict the outputs of following code
fragments if the file has been opened in filepointer file1 with the following
code :
(a)
print("A. Output 1")
print(file1.read())
print()
(b)
print(file1.readline())
print()
(c)
print(file1.read(9))
print()
(d)
print(file1.readline(9))
(e)
print(file1.readlines())
print()
NOTE. Consider the code fragments in succession, i.e., code (b) follows code
(a), which means changes by code (a) remain intact when code (b) is
executing. Similarly, code (c) follows (a) and (b), and so on.
Answer
Output
A. Output 1
B. Output 2
C. Output 3
D. Output 4
[]
Explanation
After executing file1.read() in code snippet (a), the file pointer will be moved
to the end of the file (EOF) because all the content has been read. Therefore,
subsequent read operations, such as file1.readline(), file1.read(9), and
file1.readlines(), will start from the end of the file (EOF) and will not read any
further content, resulting in empty outputs for those print statements.
Question 6
This code opens a CSV file named contacts.csv in append mode, as indicated
by the mode "a". This mode allows new data to be added to the end of the
file without overwriting existing content. It then prompts the user to enter a
name and a phone number through the console using the input() function.
After receiving input, it concatenates the name and phno separated by a
comma, and appends a newline character '\n' to signify the end of the line.
Finally, it writes this concatenated string to the CSV file using
the write() method of the file object. This operation effectively adds a new
record to the CSV file with the provided name and phone number.
Question 7
Consider the file "contacts.csv" created in above Q. and figure out what the
following code is trying to do?
if name in line:
print(line)
Answer
The code asks the user to enter a name. It then searches for the name in
"contacts.csv" file. If found, the name and phone number are printed as the
output.
Explanation
1. name = input("Enter name :") — This line prompts the user to enter a
name through the console, and the entered name is stored in the
variable name.
3. for line in file: — This line initiates a for loop that iterates over each
line in the file handle (file represents the opened file object), which
enables interaction with the file's content. During each iteration, the
current line is stored in the variable line.
4. if name in line: — Within the loop, it checks if the inputted name exists
in the current line using the in operator.
5. print(line) — If the name is found in the current line, this line prints the
entire line to the console.
Question 8
Consider the file poemBTH.txt and predict the output of following code
fragment. What exactly is the following code fragment doing ?
f = open("poemBTH.txt", "r")
nl = 0
for line in f:
nl += 1
print(nl)
Answer
The code is calculating the number of lines present in the file poemBTH.txt.
Output
Explanation
3. for line in f: — By iterating over the file handle using a for loop as
shown, we can read the contents of the file line by line.
5. print(nl) — After the for loop completes, this statement prints the value
of nl, which represents the total number of lines in the file.
Question 9
Write a method in Python to read the content from a text file diary.txt line by
line and display the same on screen.
Answer
def diary_content(f):
while str:
str = myfile.readline()
myfile.close()
diary_content("diary.txt")
Question 10
Write a method in Python to write multiple line of text contents into a text file
mylife.txt.line.
Answer
def write_to_file(file_path):
lines_to_write = ["The sun sets over the horizon.", "Birds chirp in the
morning.", "Raindrops patter on the roof.", "Leaves rustle in the breeze."]
file.write(line + '\n')
write_to_file("mylife.txt.line")
Question 11
import pickle
pickle.dump(ID, fin)
fin.close()
fout = open("Emp.pkl",'rb')
ID = pickle.load(fout)
print(ID[5])
Answer
Output
Dunzo
Explanation
1. import pickle — Imports the pickle module, which is used for serializing
and deserializing Python objects.
5. fin.close() — Closes the file fin after writing the pickled data.
6. fout = open("Emp.pkl", 'rb') — Opens the file Emp.pkl again, this time
in binary read mode ("rb"), to read the pickled data.
Question 12
import pickle
List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]]
List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
f.write(List1)
f.write(List2)
List1 = pickle.load(f)
print(List1)
Answer
The code raises an error because write() function does not work in binary file.
To write an object on to a binary file dump() function of pickle module is
used.
Question 13
What is the output of the following considering the file data.csv given below.
901242;Riya;Verma
207074;Laura;Grey
408129;Ali;Baig
934600;Manit;Kaur
507916;Jiva;Jain
import csv
data = csv.reader(f)
if 'the' in row :
print(row)
Answer
Explanation
Question 14(a)
import csv
f = open('attendees1.csv')
csv_f = csv.writer(f)
Answer
import csv
f = open('attendees1.csv') #error
csv_f = csv.writer(f)
To use the csv.writer() function, the file should be opened in write mode ('w').
The corrected code is :
import csv
f = open('attendees1.csv', 'w')
csv_f = csv.writer(f)
Question 14(b)
import csv
f = open('attendees1.csv')
csv_f = csv.reader()
for row in csv_f:
print(row)
Answer
import csv
f = open('attendees1.csv') #error 1
print(row)
import csv
f = open('attendees1.csv', 'r')
csv_f = csv.reader(f)
print(row)
Question 15
import pickle
pickle.dump(data)
Answer
import pickle
pickle.dump(data) #error 2
import pickle
pickle.dump(data, f)
Question 1
Write a program that reads a text file and creates another file that is identical
except that every sequence of consecutive blank spaces is replaced by a
single space.
Answer
for line in f:
modified_line = ' '.join(line.split())
fout.write(modified_line + '\n')
Question 2
Answer
Athletics - Rahul
Swimming - Tanvi
Athletics - Akash
Cycling - Kabir
Athletics - Riya
if event == 'Athletics':
f_out.write(line)
filter_records('sports.dat', 'Athletic.dat')
Athletics - Rahul
Athletics - Akash
Athletics - Riya
Question 3
Arvind 7258031
Sachin 7259197
The names contain only one word, the names and telephone numbers are
separated by white spaces. Write program to read a file and display its
contents in two columns.
Answer
Arvind 7258031
Sachin 7259197
Karuna 8479939
f = file.readlines()
for line in f:
Output
Arvind 7258031
Sachin 7259197
Karuna 8479939
Question 4
Write a program to count the words "to" and "the" present in a text file
"Poem.txt".
Answer
to_count = 0
the_count = 0
words = line.split()
if word.lower() == 'to':
to_count += 1
the_count += 1
Output
count of 'to': 4
count of 'the': 5
Question 5
Example :
If the file content is as follows :
Updated information
As simplified by official websites.
Answer
Updated information
def AMCount(file_path):
count_a = 0
count_m = 0
ch = ' '
while ch:
ch = file.read(1)
ch_low = ch.lower()
if ch_low == 'a':
count_a += 1
count_m += 1
print("A or a:", count_a)
AMCount("STORY.TXT")
Output
A or a: 4
M or m: 2
Question 6
Answer
text = file.read()
count = 0
if char.isupper():
count += 1
print(count)
Output
Question 7
Write a program that copies one file to another. Have the program read the
file names from user ?
Answer
def copy_file(file1, file2):
destination.write(source.read())
copy_file(source_file, destination_file)
Question 8
Write a program that appends the contents of one file to another. Have the
program take the filenames from the user.
Answer
destination.write(source.read())
append_file(source_file, destination_file)
Question 9
Write a method in python to read lines from a text file MYNOTES.TXT, and
display those lines, which are starting with an alphabet 'K'.
Answer
def display_lines(file_name):
line = file.readline()
while line:
if line.strip().startswith('K'):
print(line.strip())
line = file.readline()
display_lines("MYNOTES.TXT")
Output
Question 10
Answer
def DISPLAYWORDS(file_name):
words = line.split()
for word in words:
if len(word) < 4:
print(word)
words = line.split()
if len(word) < 4:
print(word)
DISPLAYWORDS("STORY.TXT")
Output
was
boy
Jay
He
had
dog
Leo
Question 11
Write a program that reads characters from the keyboard one by one. All
lower case characters get stored inside the file LOWER, all upper case
characters get stored inside the file UPPER and all other characters get
stored inside file OTHERS.
Answer
ans = 'y'
if char.islower():
lower_file.write(char + "\n")
elif char.isupper():
upper_file.write(char + "\n")
else:
others_file.write(char + "\n")
lower_file.close()
upper_file.close()
others_file.close()
Output
Enter a character: e
Enter a character: A
Enter a character: D
Enter a character: c
Enter a character: 7
Enter a character: @
Want to enter a character? (y/n): n
Question 12
Write a function in Python to count and display the number of lines starting
with alphabet 'A' present in a text file "LINES.TXT". e.g., the file "LINES.TXT"
contains the following lines:
There is a playground.
Answer
There is a playground.
def count_lines(file_name):
count = 0
with open(file_name, 'r') as file:
if line.strip().startswith('A'):
count += 1
print(count)
count_lines("LINES.TXT")
Output
Question 13
Answer
count = 0
while True:
char = file.read(1)
break
count += 1
print(count)
Output
78
Question 14
Write a program that will create an object called filout for writing, associate it
with the filename STRS.txt. The code should keep on writing strings to it as
long as the user wants.
Answer
ans = 'y'
filout.write(string + "\n")
Output
Hello
world!
Question 15
Answer
import pickle
pickle.dump(member1, file)
pickle.dump(member2, file)
file.close()
write_member()
Question 16
Answer
import pickle
def search_and_display_staff(staff_code):
found = False
try:
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:", staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
Output
Staffcode: S0105
Name: Aditya
Question 17
Answer
import pickle
def company(comp_id):
found = False
try:
while True:
company_data = pickle.load(file)
if company_data['CompID'] == comp_id:
print("Turnover:", company_data['Turnover'])
found = True
except EOFError:
if found == False:
else:
print("Search Successful")
file.close()
company('1005')
Output
Turnover: 900000
Question 18
Write a function to search and display details of all trains, whose destination
is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is
containing the objects of the following dictionary type:
Answer
import pickle
def search_trains():
found = False
try:
while True:
trains = pickle.load(file)
if trains['To'] == "Delhi":
found = True
except EOFError:
if found == False:
else:
print("Search Successful")
file.close()
search_trains()
Output
From: Mumbai
To: Delhi
From: Chennai
To: Delhi
From: Pune
To: Delhi
Search Successful
Question 19
(i) Write a user defined function CreateFile() to input data for a record and
add to Book.dat.
Answer
Let the file "Book.dat" include following data:
import pickle
def CreateFile():
pickle.dump(record, file)
file.close()
def CountRec(authorName):
count = 0
found = False
try:
while True:
record = pickle.load(file)
if record[2] == authorName:
count += 1
found = True
except EOFError:
if found == False:
else:
print("Search successful")
file.close()
return count
CreateFile()
Output
Search successful
Question 20
Answer
def Show_words(file_name):
words = line.strip().split()
if len(words) == 5:
print(line.strip())
Show_words('NOTES.TXT')
Output
Question 21
Write a Python program to read a given CSV file having tab delimiter.
Answer
Kavya 25 Female
Kunal 30 Male
Nisha 28 Female
import csv
print(row)
Output
['Kavya 25 Female']
['Kunal 30 Male']
['Nisha 28 Female']
Question 22
Write a Python program to write a nested Python list to a csv file in one go.
After writing the CSV file read the CSV file and display the content.
Answer
import csv
writer = csv.writer(file)
writer.writerows(data)
def read_csv(file_name):
reader = csv.reader(file)
write_nested_list(nested_list, 'output.csv')
print("Content of 'output.csv':")
read_csv('output.csv')
Output
Question 23
Write a function that reads a csv file and creates another csv file with the
same content, but with a different delimiter.
Answer
Product,Price,Quantity
Apple,1.99,100
Banana,0.99,150
Orange,2.49,80
import csv
data = list(reader)
writer.writerows(data)
Contents of "modified.csv":
Product|Price|Quantity
Apple|1.99|100
Banana|0.99|150
Orange|2.49|80
Question 24
Write a function that reads a csv file and creates another csv file with the
same content except the lines beginning with 'check'.
Answer
check1,10,A
check2,20,B
data1,30,C
check3,40,D
data2,50,E
import csv
reader = csv.reader(f_in)
writer = csv.writer(f_out)
if not row[0].startswith('check'):
writer.writerow(row)
filter('input.csv', 'output.csv')
Contents of "output.csv":
data1,30,C
data2,50,E
Question 25
Give any one point of difference between a binary file and a CSV file.
Write a Program in Python that defines and calls the following user defined
functions :
(a) add(). To accept and add data of an employee to a CSV file 'furdata.csv'.
Each record consists of a list with field elements as fid, fname and fprice to
store furniture id, furniture name and furniture price respectively.
(b) search(). To display the records of the furniture whose price is more than
10000.
Answer
The difference between a binary file and CSV file is that binary files are used
for storing complex data in a non-human-readable format and they store
data in a sequence of bytes, while CSV files are plain text files used for
storing structured tabular data in a human-readable text format.
import csv
def add():
writer = csv.writer(file)
def search():
found = False
reader = csv.reader(file)
print()
found = True
if found == False:
add()
search()
Output
Furniture ID: 1
Furniture ID: 2