File Handling in Python Question Answer
Type B: Application-based Questions
Question – 1: How following codes different from one another?
(a) | (b) |
my_file = open(‘poem.txt’, ‘r’) my_file.read() | my_file = open(‘poem.txt’, ‘r’) my_file.read(100) |
Answer: In code (a) read(), reads the entire file, while in code
(b) read(100), reads the first 100 bytes/characters from a file ‘poem.txt’.
Question – 2: If the file ‘poemBTH.txt’ contains the following poem, then What output was produced by both the code fragments given in question – 1
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the World.
Hail, mother of religions, Lotus, scenic beauty, and sages!
Answer: No output, in both code print() statements, is not written.
Question – 3: Consider the file poemBTH.txt given above. What output will be produced by following code fragments?
obj1 = open("poemBTH.txt", "r")
s1 = obj1.readline()
s2 = obj1.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
Answer: Output:
onfining countr
ies
Question – 4: Write the code to open file contacts.txt with shown information and print it in the following form:
Name : <name> Phone : <phonenumber>
Sample Data: contacts.txt
Ravi, 9898989898
Mohan Kumar, 8197586984
Answer: Python Code
contact = open("contacts.txt", "r")
line = " "
while True:
line = contact.readline()
if line =="":
break
words = line.split(',')
print("Name : ",words[0], "\t", "Phone : ",words[1])
contact.close()
Question – 5: Consider the file “poemBTH.txt” and predict the outputs of the following code fragments if the file has been opened in file pointer file1 with the following code:
file1 = open(“E:\\mydata\\poemBTH.txt”, “r+”)
NOTE: The above-all outputs are given on the basis of codes written separately.
(a)
print("A.Output 1")
print(file1.read())
print()
Answer: A.Output 1
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the World.
Hail, mother of religions, Lotus, scenic beauty, and sages!
(b)
print("B.Output 2")
print(file1.readline())
print()
Answer: B.Output 2
God made the Earth;
(c)
print("C.Output 3")
print(file1.read(9))
print()
Answer: C.Output 3
God made
(d)
print("D.Output 4")
print(file1.read(9))
print()
Answer: D.Output 4
God made
(e)
print("E.Output 5")
print(file1.readlines())
print()
Answer: E.Output 5
[“God made the Earth;\n”, “Man made confining countries\n”, “And their fancy-frozen boundaries.\n”, “But with unfound boundless Love\n”, “I behold the borderland of my India\n”, “Expanding into the World.\n”, “Hail, mother of religions, Lotus, scenic beauty, and sages! \n”]
Note: If all codes are written in Succession, then the output is:
A.Output 1
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the World.
Hail, mother of religions, Lotus, scenic beauty, and sages!
[]
Question – 6: What is the following code doing?
file = open("contacts.csv", "a")
name = input("Please enter name.")
phno = input("Please enter phone number.")
file.write(name + " , " + phno + "\n")
Answer: This code will create a text file named “contact.csv” and write one row in the file containing name and phno which entered by user at the time of program execution.
Question – 7: Consider the file “contacts.csv” created in the above Q. and figure out what the following code is trying to do?
name = input("Enter name :")
file = open("contacts.csv", "r")
for line in file:
if name in line:
print(line)
Answer: The above code first asked to enter a name, then it read the records/data/line from a text file named “contact.csv”, and display that line which contains the name (entered by user).
Question – 8: Consider the file poemBTH.txt and predict the output of the 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: This program will count the number of lines in poemBTH.txt file. The output of the above code is: 7
Question – 9: If you use the code of Q.8 with p1.txt(created in solved problem 14), what would be its output?
Answer: Output is 5
Question – 10: 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: Python code to read a text file line by line is
#Method - 1
def readFileLinebyLine():
fobj = open("diary.txt")
line = " "
while line:
line = fobj.readline()
print(line, end= ' ')
fobj.close()
#Method - 2
def readLinebyLine( ):
fobj = open("diary.txt")
for line in fobj:
print(line, end= ' ')
fobj.close()
Question – 11: Write a method in Python to write multiple lines of text contents into a text file mylife.txt.line.
Answer: Python Code:
def writeMultiLine( ):
fobj = open("mylife.txt")
multiline = '''Hello I am
multiline text'''
fobj.write(mulitline)
fobj.close()
Question – 12: What will be the output of the following code?
import pickle
ID = {1: "Ziva" , 2: "53050" , 3: "IT" , 4: "38" , 5: "Dunzo"}
fin = open("Emp.pkl", "wb")
pickle.dump(ID , fin)
fin.close()
fout = open("Emp.pkl", 'rb')
ID = pickle.load(fout)
print( ID [5] )
Answer: Dunzo
Question – 13: What will be the output of the following code?
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]]
with open('data.pkl', 'wb') as f:
f.write(List1)
with open('data.pkl', 'wb') as f:
f.write(List2)
with open('data.pkl', 'rb') as f:
List1 = pickle.load(f)
print(List1)
Answer: Errors in the above code, in line number 6 and 8. write( ) function can not be used with binary file. It should be pickle.dump().
After doing needed correction in the code the output is
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]]
with open('data.pkl', 'wb') as f:
pickle.dump(List1,f)
with open('data.pkl', 'wb') as f:
pickle.dump(List2,f)
with open('data.pkl', 'rb') as f:
List1 = pickle.load(f)
print(List1)
Output:
[‘Rita’, {‘x’: 45, ‘y’: False}, (9, 5, 3), [[‘insects’, ‘bees’], None]]
Question – 14: What will be the output of the following considering the file data.csv given?
File data.csv contains
Indetifier;First name;Last name
901442;Riya;Verma
207074;Laura;Grey
408129;Ali;Baig
934600;Manit;Kaur
507916;Jiva;Jain
Python Code:
import csv
with open('data.csv', 'r+') as f:
data = csv.reader(f, delimiter = ';') #delimiter is required when comma is not a separator.
for row in data:
if 'Ali' in row:
print(row)
Answer: Output: No Output No line is having ‘the’
Question – 15: Identify the error in the following code:
(a)
import csv
f = open('attendees1.csv')
csv_f = csv.writer(f)
Answer: By default open() function open the file in read mode, but in the code we try to create an object of writer.
(b)
import csv
f = open('attendees1.csv')
csv_f = csv.reader()
for row in csv_f:
print(row)
Answer: file object name is missing in csv.reader() statement. It should be csv.reader(f)
Question – 16: Identify the Error in the following code
import pickle
data = ['one', 2, [3, 4, 5] ]
with open('data.dat', 'wb') :
pickle.dump(data)
Answer: In line number 3 missing as fileobject. In line number 4 fileobject name is missing.
import pickle
data = ['one', 2, [3, 4, 5] ]
with open('data.dat', 'wb') as fobj:
pickle.dump(data, fobj)