Python File Handling Questions
Python File Handling Questions
PYTHO
234 (THON -NI
bjective Type Questions
OTAs
Multiple Choice Questions
is called a
[Link] stored on a storage device with a specific name
(a) file = open("c:\ \[Link]", "a") (b) file open("c:\ \[Link]", "rw")
=
To read the next line of the file from a file object infi, we use
(6) In rt mode, the pointer is initially placed at the beginning of the file and for wt
placed at the end. pointer" ,
(c) In w+ mode, the pointer is initially placed at the beginning of the file and for
placed at the end.
(d) Depends on the operating system.
HANDLING
FILE
hapter 5:
235
ch of the followin
Which following Command is used to
16. open a file
read-mode only "c:\[Link]" in ?
(a) fin = open("c: \[Link]", "r")
6) fin open("c:\\[Link]", "r") =
( c ) f i n o p e n ( f i l e = "c:\[Link]", "T+")
(d) fin open(file "c:\\[Link]", "r+")
= =
ich of the following statements are true regarding the opening modes of a file ?
(oWhen you open a file for reading, if the file does not exist, an error occurs.
(h)When you open a file for writing, if the file does not exist, an error occurs.
(c) When you open a file for reading, if the file does not exist, the program will open an empty file.
(d When you open a file for writing, if the file does not exist, a new file is created.
)When you open a file for writing, if the file exists, the existing file is overwritten with the new file.
18. Which of the following command is used to open a file "e:[Link] for writing in binary format only ?
(a) fout open("c:\[Link]", "w") (b) fout open("e:\\[Link]", "wb"
c)fout open("c:\[Link]", "w+") (a) fout open("c:\\[Link]", "wb+")
19. Which of the following command is used to open a file "c:\[Link]" for writing as well reading in
file mode will open a file for read and write purpose.
5. The
file mode will open a file for write and read purpose.
6. The
method is used.
7. To close an open file,
list, method is used.
8. To read all the file contents in the form of a
is
21. The file mode to open a text file for writing as well reading .
22. The file mode to open a binary file for writing as well reading 1s
23. The file mode to open a csv file for reading as well writing8is
24. The file mode to open a csv file for appending as well reading is ,
NOTE Answers for 0TQs are given at the end of the book.
Solved Problems
print([Link]())
Write a function stats( ) that accepts a filename and reports the file's longest line.
7.
Solution.
def stats(filename)
longest = ""
Solution. [WHY
11. What is the output of following code?
file("e:\\poem. txt", "r").readline ()
Solution. WHY? \n
rec
while True:
rec [Link]()
" "
if rec ==
break
count = count + 1
239
The file
"[Link]" contains the following
15 Better than Heaven or Arcadia
I love thee, O my India!
And thy 1ove I shall give
To every brother nation that lives.
Considering the given file, wat output will be produced by the following code ?
obj1-open("[Link]", "r")
s1 [Link]()
s2 = [Link]()
s3 obj1. readline ()
s4 [Link](15)
print(s4)
[Link]()
Solution. The output produced by above code is And thy love I
16, Two identical files ([Link] and [Link]) were created by following two codes (carefully go through the two codes
given below).
(a) obj open("[Link]", "w")
[Link]("Better than Heaven or Arcadia")
[Link]("I love thee, O my India!")
[Link]("And thy love I shall give")
[Link]("To every brother nation that lives. ")
[Link])
(6) obj = open("[Link]", "w")
[Link]()
240 COMPUTER SCIENCE WITH PYTHON
Solution. No output or blank output will be produced by code (a).
For code(b), the output produced will be
Better than Hea
18. Consider file [Link] created above. Now predict the output
the offollowing code that works with [Link]. Emla
the reason behind this output. .Explain
fp1 open("[Link]", "r")
print([Link](20))
s1 [Link] (30)
print(s1)
print([Link](25))
Solution. The output produced by above code will be
A poem by Paramhansa
Yogananda
Better than Heaven or Arc
The reason behind this output is that the first file-read line (i.e., [Link](20), read 20 bytes
from the file pointer. As just after opening the file, the file-pointer is at the beginning of the
file, the 20 bytes are read from the beginning of the file which returned string as "A poem by
Paramhansa \n" - this is because readlinel) returns the read string by adding an end-line character to
it (\n). So the first line of output was printed as:
A poem by Paramhansa
After the first readlinel ), the file poinier was at the space following word Paramhansa', so the next
readline( ) started reading from there and read 15 character or end-of the-line, whichever is earlier. So
the read string was "Yoganandaln" - notice the space before word Yogananda. Hence came the
second line of the output.
Now the file-pointer was at the beginning of the third line and the next readline (ie,
[Link](25)) read 25 characters from this line and gave the last line of output.
19. A textfile contains alphanumeric text (say [Link]). Write a program that reads this text file and prints only the
numbers or digits from the file.
Solution.
F open("[Link]", "r")
for line in F:
words = [Link]()
for i in words:
for letter in i:
if([Link](O):
print (letter)
20. Read the code given below and answer the question:
fh open("[Link]", "W)
[Link]("Bye")
[Link]() ?
tnis
fthe contains "GOOD" before execution, what will be the contents
file after execution of
of thefile
Solution. The file would now contain "Bye" only, because when an existing file is opened
mode ("w"), it truncates the existing data the file.
HANDLING
Chopter
5: FILE
241
Write afunction Python in to count
the number of What would be the
lines in a text file '[Link]' which is starting output of following code?
fh open
with an alphabet 'A' ICBSE Sample Paper 2019-201
.
("[Link]", "r")
lst [Link] ()
Solution.
print(lst[0], end = ")
def COUNTLINES(): print(lst[2], end = '')
file open("[Link]', 'r*) print(lst[5], end = '')
lines [Link]() print(lst[1], end = '")
count e print(lst[4], end = '")
for w in lines:
if w[e] == "A" or w[0] == "a"
print(1st[3])
Solution.
count count + 1
Line 1\n
print("Total lines started with 'A' or 'a", count)
Line 3
[Link]() Line 6 \n
22. Write a function in Python that counts the number n
of "Me" or "My" words present in a text file Line 4
[Link]". f the "[Link]" contents 24. Write code to print just the last line of a text file
aTe as follows . [CBSE Sample Paper 2020-21] "[Link]".
My first book Solution.
was Me and fin =open ("[Link]", "r")
linelist = [Link]()
My Family. It
gave me
print ("Last line =", linelist[-1])
chance to be 25. Write a program that copies a text file "[Link]"
Known to the onto "[Link]" barring the lines starting with a
Eo
storing the file contents on the disk. By default text files are stored
with some text
translation is one of these. By specifying newline =" as argument to file open() function, weensu
translations
that no EOL translation takes place. This is useful when we use the files on different platforms
32. What does [Link] object do ?
Solution. The [Link] object adds delimitation to the user data prior to storing data in the c
on storage disk.
Afle [Link] contains the text as shown in Fig. 5.5 in the chapter. Write a program to remooe all thelines
shat comtain the character 'a' in this file and write other lines into another file.
Solution.
myfile = open("[Link]", "r")
newfile = open("[Link]", "w")
[Link](line)
[Link]()
[Link]()
line =
whileline: file
#one line read from
line =newfile. readline ()
print(line)
[Link]()
never occur.
we know this wil1 this single most powerful
1letter.
f=open
(1) ('diary. txt', 'r')
Solution.
in read mode.
() The text file [Link] is opened
in write mode.
(1) The text file [Link] is opened
code?
37. What will be displayed by the following
import pickle 'fourth', 'Fifth']
'second', 'third',
Names ['First',
lst []
:
for i in range(-1, -5, -1)
[Link](Names[i]) as fout:
with open( '[Link]', 'wb')
[Link](1st, fout)
'rb') as fin:
with open('[Link]',
nlist [Link](fin)
print(nlist)
'third', 'second']
['Fifth', 'fourth',
Solution.
244 COMPUTER SCIENCE WITH PYTHON K
38. Following code is written to update a record in a file opened with follorwing code
import pickle
fin =open( "[Link]', 'rb+')
try:
while True:
_ = [Link]() #Line 1 : store file-pointer position before reading the record
[Link](fin)
if stu[ Marks'] in [92, 93, 94]
stu[ 'Marks ' ] += 3 # changes made in the record
fin._ # Line 2 :place the file-pointer at the exact location of the recond
[Link](stu, fin) # now write the updated record on the exact 1ocation
except
open("[Link]", "r")
lcount 0
#initially stored a space ( a non-None value)
#variable to store count of lowercase letters
ucount= 0
print(line)
the of the
text file [Link], to find and display
occurrence
print ( count)
[Link]()
246 COMPUTER SCIENCE WITH
PYTHONON - X
try:
while True:
[Link] (fobj)
rec
i frec[2]> 75:
print(rec[0], rec[1], rec[2], sep= "\t")
num =
num +1
except:
[Link]()
return num
49. Write a function Show_words() in python to read the content of a text file [Link]' and display the
entire content in capital letters. CBSE 2020C]
Example, if the file contains:
This is a test file
Then the function should display the output as
THIS IS A TEST FILE
HANDLING
5: FILE
Chapter
247
Solution. def Show_words ():
file open( "[Link]', 'r)
=
Lines [Link] ()
for L in Lines:
print([Link] ())
[Link]()
Write a
50. program to increase the salary by Rs. 2000/-of the employee having empno as 1251 in the file [Link].
Solution.
import pickle
print(empp)
found True
except EOFError:
if found == False:
high
Word =
existing =[]
for w in wordlist
Wcount = [Link](w)
if w not in existing:
[Link]( [w,wcount ])
[Link](w)
248 COMPUTER SCIENCE WITH PYTHON
if wcount > high:
high wcount
Word = w
print("The word '"+ Word+"' occurs maximum number of times, " , high, "times, "
print("\nOther words have these frequencies: ")
print (wordfreq)
For the text file [Link] shown below, the above program produced the following outot
Jan gan man adhinayaka jaya he
Bharat bhagya vidhata
Panjab Sindh Gujarat Maratha
Dravid Utkal Banga
Vindhye Himacha1 Yamuna Ganga
Uchchal jaladhi tarang
Tava shubh name jage,
Tava shubh ashish mange,
Gahe tava jaya gatha.
Jan gan mangal dayak jaya he
Output:
The word Jaya' occurs maximum number of times, 7 times. Other wordss have these frequencies
[['Jan', 2]. ['gan', 2]. [ 'man', 1], ['adhinayaka', 1]. ['jaya', 3]. [ 'he', 6],
[ Bharat', 2], ['bhagya', 2], [ 'vidhata', 2]. ['Panjab', 1]. ['Sindh', 1]. ['Gujarat', 1],
[ Maratha', 1]. [ 'Dravid', 1]. ['Utkal', 1]. [ "Banga', 1], [ 'Vindhye', 1].[Himachal', 1],
['Yamuna', 1], ['Ganga', 1], ['Uchchal', 1]. ['jaladhi', 1], ['tarang', 1], [Tava', 2],
['shubh', 2]. ['name', 1], ['jage, ', 1],['ashish', 1]. ['mange,', 1], ['Gahe', 1],
['tava', 1], ['gatha. ', 1], ['mangal', 1], ['dayak', 1], ['Jaya', 7]1]
52. Write a program to read following details of sports' performance (sport, competitions, prizes-won) ofyou
school and store into a cso file delimited with tab character
Solution.
import csv
fh open("[Link]", "w")
Swriter = [Link](fh, delimiter="'\t')
[Link]([ 'Sport', 'Competitions', "Prizes won' ]) #write header row
ans 'y'
i = 1
sport name:Tennis
NO. of competitions participated:14
prizes won:9
want to enter more records? (y/n)..y
Record 2
sport name: Footbal1 Eile Edit Format Yew Help
NO. of competi tions participated:22 Sport Competitions Prizes won
Tennis 14 9
Prizes won: 16
Football1 22 16
want to enter more records? (y/n)..y Chess 25 15
Record 3
Sport name: Chess
NO. of competitions participated:25
Prizes won: 15
Want to enter more records? (y/n)..n
Write a program to get item details (code, description and price) for multiple items from the user and create a
53.
csu file by writing all the item details in one g0.
Solution. import csv
fh open("[Link]", "w")
iwriter = [Link] (fh)
ans = 'y'
itemrec= [['Item_Name', 'Description', 'Price']]
print("Enter item details")
while ans =='y':
iname input("Enter Item code:")
desc input("Enter description:")
price float (input ( "Enter price: "))
[Link]( [iname, desc,
price])
to enter more items? (y/n)...")
ans =
input ("Want
else
[Link](itemrec)
written successfully. ")
print( "Records
[Link]()
Enter price:15
more items? (y/n)..Y
Want to enter
Enter Item code RO5
Enter description Ruler
Enter price:20
items? (y/n)...n
Want to e n t e r more
Records written successfully.
250 COMPUTER SCIENGE WITH
PrTHO
GLOSSARY
File A bunch of bytes stored on some storage device
File mode A constant describing how a file is to be used.
Stream A sequence of bytes
For
Assignment 8electhve hasinpaness
Solutions
Type A: Short Answer Questions/Conceptual Questions
1. What is the difference between "w" and "a" modes?
2. What is the significance of a file-object ? Scan
3. How is file open() function different from close( ) function ? OR Code
4. Write statements to open a binary ile C:\Myfiles\[Link] in read and write mode by speciftying the
file path in two different formats.
5. When a file is opened for output in write mode, what happens when
(i) the mentioned file does not exist (ii) the mentioned file does exist?
6. What role is played by file modes in file operations ? Describe the various file mode constants and ther
meanings.
7. What are the advantages of saving data in: ) binary form (Gi) text form (ii) csv files?
8. When do you think text files should be preferred over binary files ?
9. Write a statement in Python to perform the following operations CESE D14
(a) To open a text file "[Link]" in read mode
(6) To open a text file "[Link]" in write mode
10. When a file is opened for output in append mode, what happens when
() the mentioned file does not exist (ii) the mentioned file does exist.
11. How many file objects would you need to create to manage the following situations ? Explain
(i) to process three files sequentially (1) to merge two sorted files into a third file.
12. Is csv file different from a text file ? Why/why not ?
13. Is csv file diferent from a binary file ? Why/why not ?
14. Why are csv files popular for data storage ?
15, How do you change the delimiter of a csv file while writing into it ?
16. When and why should you suppress the EOL translation in csv file handling ?
17. If you rename a text file's extension as .csv, will it become a csv file ? Why/why not ?
18,
Differentiate
difference
between
"w and "r" file modes used in
Python while opening a data file. lustrate the
using
suitable examples. ICBSE 2020C
251
2, If
ihe file
the '[Link]
[Link] contains
contain the
following poem (by Paramhans Yoganand)
God made the Earth;
Man made confining countriess
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, scentc beauty, and sages
Then what outputs will be produced by both the code fragments given in questionl.
Consider the file [Link] given above (in previous question). What output will be produced by
3.
code fragment ?
following
obj1 open("[Link]", "r")
s1 [Link]()
[Link](10)
s3 [Link](15)
print(s3)
print([Link] ())
[Link]()
form:
file [Link] with shown information and print it in following
4. Write code to open
Name:<name> Phone<phonenumber>
following code fragments if the file has
and predict the outputs of
5. Consider the file "[Link]"
with the following code:
been opened in filepointer file1
"r+")
open( "E: \ \mydata\\[Link]",
file1 =
[Link](ID, fin)
[Link]()
fout open("Emp.pk1", 'rb')
ID =pickle. load (fout)
print( ID [5])
13. What will be the
output of the following code ?
import pickle
Listi [ Roza', {'a': 23, 'b':
True), (1, 2, 3), [['dogs', 'cats'], None] ]
List2 [ Rita', {'x' : 45,
'y' : False}, (9, 5, 3), [['insects',
with open( "[Link]', 'wb') as f: 'bees '], None]1
[Link](List1)
with open( "[Link]', 'wb') as f:
[Link](List2)
with open( '[Link]', 'rb') as f:
List1 [Link] (f)
print(List1)
14. What is the output of the following considering the file [Link]
given on the right.
import csv
with open('C:
data = [Link](f)
\[Link]', 'r+') as f:
File [Link] contains:
for row in data:
if 'the' in row | ldentifierFirst name;Last name
print (row) 901242:Riya; Verma
15. Identify the error in the 207074:Laura; Grey
following code.
408129;Ali:Baig
(a) import csv 934600 Manit; Kaur
f open( '[Link]')
507916Jiva,Jain
Csv_f [Link](f)
(b) import csv
f open('[Link]')
cSv_f = [Link]()
for row in csv_f:
print(row)
5 : FILE HANDLING
hopter
253
in the
16. Identif
the error
following code.
import pickle
data ['one, 2, [3, 4, 5]]
with open("[Link]', 'wb'
[Link](data)
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.
4Write a program to count the words "to" and "the" present in a text file "[Link]".
5. Write a function AMCount( ) in Python, which should read each character of a text file [Link],
should count and display the occurrence of alphabets A and M (including small cases a and m too).
CBSE Sample Paper 2020-21]
content is as follows
Example: If the file
Updated information
A or a:4
M or m : 2
in a text file "[Link]".
. Writeprogram to count
a the number of upper-case alphabets present
read the file n a m e s from user ?
to another. Have the program
Write a program that copies one file take the filenames
file to another. Have the program
Write a program that appends
the contents one of
from the user. and
lines from a text file [Link],
DISPLAYWORDS() in python to read
9. a method/function ICBSE Sample Paper 2020)
Write less than 4 characters.
display those words, which are
one by o n e . All
lower case characters get
10. reads characters
from the keyboard file UPPER and all other
ite a program thatLOWER, all upper case characters get stored inside the
Ored inside the file
characters get stored inside file OTHERS. with alphabet A' present
and display the number of lines starting lines:
e function in Python to count
a contains the following
file "[Link]"
" a text file [Link]". e.g., the
"
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
allowed in password
ALphabets & numbers are
as 3. file.
the
function should display the output the first $ in
a text
of characters up to
12. Write counts the number
aprogram that
COMPUTER SCIENCE WITH PYTHON
254
object called filout for writing, associate it with #ha
13. Write a program that
will create an
writing strings to it as long as the user wants.
ilename
[Link]. The code should keep on
method in python to write the
Consider the following definition
of a dictionary Member, write a the content e.
14.
in a pickled file [Link].
(similar Delhi 2015
to
'
Name':
Member {'MemberNo.
=