0% found this document useful (0 votes)
2 views21 pages

Python File Handling Questions

The document contains a series of objective type questions related to file handling in Python, including multiple choice, fill in the blanks, and true/false questions. It covers topics such as file modes, reading and writing files, and the differences between text and binary files. Additionally, it includes solved problems and solutions that illustrate practical applications of file handling concepts.

Uploaded by

sakshyatab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Python File Handling Questions

The document contains a series of objective type questions related to file handling in Python, including multiple choice, fill in the blanks, and true/false questions. It covers topics such as file modes, reading and writing files, and the differences between text and binary files. Additionally, it includes solved problems and solutions that illustrate practical applications of file handling concepts.

Uploaded by

sakshyatab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

cOMPUTER SCIENCE WITH

PYTHO
234 (THON -NI
bjective Type Questions
OTAs
Multiple Choice Questions
is called a
[Link] stored on a storage device with a specific name

(c) file (d) tuple


(a) array (b) dictionary
format of files can be created programmatically through Python
non to store .
2. Which of the following
some data ?
(a) Data files (6) Text files
(c) Video files (d) Binary files

3 To open a file c:\[Link] for appending data, we use

(a) file = open("c:\ \[Link]", "a") (b) file open("c:\ \[Link]", "rw")
=

(d) file open(file "c:\[Link]", "w'")


=
=
(c) file = open(r"c:\[Link]", "a")

(e) file = open(file = "c:\|[Link]", "w") file open("c: \ [Link]")


=

To read the next line of the file from a file object infi, we use

(a) [Link](all) (b) [Link]() (c) [Link]() (d) [Link]()


we use
5. To read the remaining lines of the file from a file object infi,
(c) [Link]() (d) [Link]( )
(a) [Link](all) (b)[Link]()
6. The readlines() method returns
(c) a list of single characters (d) a list of integers
(a) str (b) a list of lines
7. Which of the following mode will refer to binary data ?
(a)r (b) w ()+ (d) b
what does this term means "r, a"?
S. In file handling,
6) append, read (c) all of the mentioned (d) none of these
(a) read, append
9 Which function is used to read all the characters?
(a) read() (b) readcharacters() (c) readall() (d) readchar()
10. Which function is used to read a single line from file ?

(a) readline() (b) readlines() (c) readstatement() (d) readfulline()


11. Which functiorn is used to write all the characters?

(a) write( (b) writecharacters() (c) writeall() (d) writechar()


12. Which function is used to write a list of strings in a file ?
()writestatement() (d) writefullline()
(a) writeline() (6) writelines()
13. Which of the following represents mode of both writing and reading in binary format
(a) wb+ (6) w (c)wb (d) w+
14. Which of the following is not a valid mode to open a file ?
(a) ab (b) rw (c) r+ (d) w+

15. What is the difference between rt and w+ modes ?


(a) No difference.
w t h e pointer

(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

binary format only ?


(a) fout = open("c:\ [Link]", "w") (6) fout = open("c:\ |[Link]", "wb")
(a) fout = open("c:\\[Link]", "wb+")
c)fout open("c:\[Link]", "w+")
write data in the binary format ?
20. Which of the following functions do you use to

(a)write(O (b) output() (c) dump() (d) send(


Fill in the Blanks
1. The default file-open mode is . mode.
in the opened file.
2. A governs the type of operations (e.g., read/write/append) possible
of data files can be files and files.
3. The two types
4. The other name for file object is .

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

9. To write a list in a file, method may be used.


method may be used.
10. To force Python to write the contents of file buffer on to storage file,.
module of Python is used.
11. To read and write into binary files,
binary file.
module writes data into
a
12. The method of pickle
binary file.
module reads data from
a
13. The method of pickle
or
stream is called
14. The conversion of an object hierarchy in byte
values in csv files is called the,
15. The character that separates the

16. The default delimiter of csv files is


17. The csv files are actually files
argument in open).
is text file by giving.
18. We can suppress EOL translation
is,
a binary file
for reading as well writing
19. The file mode to open
well wTiting 1s
reading as .

20. The file mode to open a text file


for
236 COMPUTER SCIENCE WITH
HON .

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 ,

25. To specify a different delimiter while writing into a csv file,


argument is used with
[Link]( ).
True/False Questions
1. When you open a file for reading, if the file does not exist, an error occurs.
2 When you open a file for writing, if the file does not exist, an error occurs.
3. When you open file for writing, if the file exists, the existing file is overwritten with the
a
new ile.
4 The absolute paths are from the topmost level of the directory structure.
5. The relative
paths are relative to the current working directory.
6. The relative path for a file
always remains the same even after changing the directory.
7. The types of
operations that can be carried out on a file depend upon the file mode a file is opened in.
8. Tf no path is
given with a file name in the file opern( ), then the file must exist in the current directory.
9. Functions readline( ) and readlines( ) are
essentially the same.
10. Python automatically flushes the file buffers before closing a file with close( ) furnction.
11. When you open a file for
writing, if the file does not exist, a new file is created.
12. When you open a file for
appending, if the file exists, the existing file is overwritten with the new file.
13. Conversion of an object hierarchy in
byte stream is called Serialisation.
14. Serialisation process is also called
pickling.
15. The load( ) function of the pickle module performs pickling.
16. The dump() functionof the pickle module performs unpickling.
17. The csv files can only take comma as delimiter.
18. The csv files are text files.

NOTE Answers for 0TQs are given at the end of the book.

Solved Problems

1. What is the difference between a text file and a binary file?


Solution. A tert file is file that stores information
a
the in codle
characters. files, each line of text is terminated with a form of a stream of ASCII or Un
In text
System) known as EOL (End of Line) character. special character (as per the Operating
A binary file is a file that stores the information in the form of a there
is no delimiter for a line and stream of bytes. In a binary nie
no character translations occur here.
2. What is the difference between read() and readlines( )function?
Solution. The read() reads from a file in read
mode, and stores its contents in a
The readlines() function, reads from a file in read mode string type variaable.
and returns a list of all lines in thefile
FILE HANDLING
Chapter 5 237

3. Differentiate between thefollowing: CBSE D 2015]


) f open( 'diary. txt', 'r' f open( [Link]', 'w')
Solution. () File has been opened in read mode with file handle f.
(i) File has been opened in write mode with file handle f

4 What is the difference between readlinet ) and readlines( ) function?


Solution. The readline() function reads from a file in read mode and returns the next line in the file
or a blank string if there are no more lines. (The returmed data is of string type)
The readlines() function, also reads from a file in read mode and returns a list of all lines in the file.
(The returned data is of list type).
5. What is the difference between write( ) and writelines( ) functions?
Solution. Both write() and writelines() work on text files. The write() function takes argument of
an iterable
string type and writes it to the file. The writelines() function, on the other hand, takes
(tuple/list/string/a python sequence) as argument and writes it to the file.
6. Write a single loop to display all the contents ofa text file [Link] after removing leading and trailing whitespaces.

Solution. for line in file("poem. txt") :

print([Link]())
Write a function stats( ) that accepts a filename and reports the file's longest line.
7.
Solution.
def stats(filename)
longest = ""

for line in file(filename)


i f len(1ine) len(longest)
longest = line

print("Longest line's length =", len(longest))


print (longest)
? Explain.
8. What is the output offollowing code fragment
out file ("[Link]", "w")
[Link]("Hello, world! \n")
[Link]("How are you?")
[Link]()
file("[Link]").read()
Hello, wor1d!\nHow are you?"
Solution. The output will be:
lines write text to the file.
is opening the file in write mode; the next two
The first line the code
of Function file() does the same
that reference reads the file-content.
The lastline opens the file and from reference to file, on which read() is applied.
will give the open
as that of open().Thus file("[Link]") and copies all lines that do not start witha
that accepts twofilenames,
9. Write a function remove_lowercasel )
into the second.
lowercase letter from the first file
outfile):
Solution. def remove_lowercase(infile,
output = file(outfile, "w")
:
for line 1in file(infile)
"abcdefghijklmnopqrstuvwxyz"
if not 1ine[®] in
[Link] (line)
[Link]()
COMPUTER SCIENCE WITH PYTHON.
238 pYTHON A
10. What is the output of following code ?
split()
file("e:\\[Link]", "r").readline().
Recall that [Link] has some leading and trailing
whitespaces.

Solution. [WHY
11. What is the output of following code?
file("e:\\poem. txt", "r").readline ()
Solution. WHY? \n

12. What is the output of following code ?


fh file("[Link]", "r")
size =
len ([Link](0))
print([Link](5))
Solution. No output
Explanation. The [Link]( ) of line 2 will read the entire file content and place the file pointer at the
end of file. For the [Link](5), it will return nothing as there are no bytes to be read from EOF thus
print() statement prints nothing.
13. Writea program to display all the records in a file along with line/record number.
Solution.
fh = open("[Link]", "r")
COunt = 0

rec

while True:
rec [Link]()
" "

if rec ==

break
count = count + 1

print(count, rec, end = "*) # to suppress extra newline by print


[Link]()
14. What is the output produced by following code ?
obj = open( "[Link]", "w")

[Link]("A poem by Paramhansa Yogananda) "

[Link]("Better than Heaven or Arcadia")


[Link]("I love thee, O my Indial")
[Link]("And thy love I shall give")
[Link]("To every brother nation that lives.")
[Link]()
obj1 open("[Link]","r")
s1 [Link](48)
print (s1)
[Link]()
Solution. The output produced by above code will be:
A poem by Paramhansa Yogananda Better than Heaven
5 : FiLE HANDLUNG

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]( "Better than Heaven or Arcadia\n")


[Link]("I love thee, O my India!\n")
[Link]( "And thy love I shall give\n")
[Link]("To every brother nation that lives.\n")
[Link]( )
following
with code.
What would be the output produced if the files are read and printed
Solution. The output produced by code (a) i l l be
India!And thy love
love thee, omy
Better than Heaven or Arcadiar
nation that 1ives.
I shal1 giveToevery brother

Theoutput produced by code (b) will be:


A poem by Paramhansa Yogananda
Better than Heaven or Arcadia
I love thee, O my India!
And thy love I shall give
1ives.
TO every brother nation that produced by
what output will be
created in previous question,
the two files [Link] and [Link]
ETIng
following code fragments ? "r")
(b) obji =open( "[Link]",
(a) obj1 open("[Link]","r") s1 =obj1.
readline()

s1 [Link]() s2 obji1. read(15)


s2 [Link](15) print (s2)
print(s2) [Link]()

[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

World. "@" sign.


The output of the function should be : Solution.
Count of Me/My in file: def filter(oldfile, newfile)
fin =open (oldfile, "r")
Solution. fout open (newfile, "w")
def displayMeMly(): while True
num 0 text [Link]()
i f len(text) == 0:
f open("[Link]", "rt")
break
N [Link] ()
i f text[e] == "@":
M= [Link]()
continue
for x in M:
[Link](text)
if x== "Me" or x = "My":
[Link])
print(x) [Link]()
num num+1 filter("source. txt", "[Link]")
[Link]() #calling the function

print("Count of Me/My in fille: ", num)


following statement. In which file
23. A given text file "[Link]" contains 26. Consider the
answer.

mode is the file opened ? Justify your


Line 1\n f:
open("poem. txt')
as
with
\n because the file mode
Line Solution. Read mode,
and the default file
Line 4 has not been specified
mode.
\n mode is the read
Line 6
COMPSTEP SIENCE WITH
242
What is its need ?
27.
27. What is pickling process ? maintained while stori.
structure which must be ing
Solution. Objects havespecific
a
module to take care of that. The.
module -
the pickle
them. Python provides special
a
so that they can be storedin 3P
serializes the objects and
converts them into byte stream binary
What is unpickling ?
28 of pickling, whereby a byte stream
the inverse operation m (oite 1
Solution. The "unpickling" is
converted back into an object
hierarchy.
from a binary file) is
text file and a
delimited text file ?
What is the difference between a regular
text in the same form as tyned .
files which store the
Solution. Regular Text files are the
the text translations take place. These.
Here the newline character ends a line and
Unicode).
a file extension [Link].
character separate the val
is stored to
alues, i
Delimited Text files are also text files where a specific
after each value, eg., a tab or a comma after every value, e.g.,
TSV files (Tab Separated Values
CSV files (Comma Separated Values files).

30. What are csv files?


Solution. CSV files are Comma Separated Values files. These are the delimited files when ma
comma (delimiter character which separates the values) is used to separate the values stored. T
CSV files can also a delimiter other than comma but comma is the default delimiter. These files t
the extension as .csv.

31. What is the significance ofnewline =


argument in file open() function ?
Solution. When newline = " ensures that no end of line (EOL) translation would take place whi.

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.

33. What is the function of [Link] object ?


noves t
Solution. The [Link] object reads data from a csv file on storage disk, parses it, L.e,
data ro
delimitation and loads the parsed data into a Python iterator wherefrom we can fetch
tne
by row.

34. What will be stored in the file [Link]


after the following code is executed?
data [[ 'DRS Delhi', 'Esha', 'Badminton'],
[ BTS Patna', 'Abhi',
import csv
'Tennis ]1
with open( 'schoo; .csv, 'w', newline =") as svfile:
writer [Link](csvfile, delimiter ',') =

[Link]( ['School', 'Nickname', 'Sport'])


[Link](data)
Solution. 'School', 'Nickname', 'Sport
DRS Delhi', 'Esha',
'Badminton
BTS Patna', 'Abhi', 'Tennis
5:
FLE HANDLING 243
Chopter

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")

line =" #initially stored a space (a non-None value)


whileline:
1ine= [Link]() # one line read from file
if 'a' not in line:

[Link](line)
[Link]()
[Link]()

print( "Newly created file contains ")


print("- -")
newfile = open( "[Link]", "r")

line =
whileline: file
#one line read from
line =newfile. readline ()
print(line)
[Link]()

The output produced by above program is

Newly created file contains

never occur.
we know this wil1 this single most powerful
1letter.

HOw mediocre our


world wOuld be wi thout
(Delhi 2015)

36. Differentiate between the following:


f open ("diary. txt', 'w')
(i) =

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

Fill in the blanks in Lines 1 and 2 to complete the code.


Solution. Line 1: position =[Link]() #can use any identifier in place of position
Line 2: [Link] (position)
39. Identify the error in the following code:
1. import pickle
2 data ['one', 2, [3, 4, 5]]
3. with open("[Link]', 'rb') as f:
[Link](data, f)
Solution. The file is opened in read mode and dump0 function tries to write onto file, hence the error.
So the line 3 should be changed to L with open( [Link]', 'wb') as f:
40. ldentify the error in the following code.
1 f open(/tmp/workfile', 'r+')
[Link]( '0123456789abcdef")
3. [Link]('xyz8466')
4. [Link]()
5. f. seek(0)
6. [Link]()
Solution. The lines 5 and 6 will raise the error as no operation can take
closed at line4. Since the file is opened in read as well write mode, we
place in a closed file fileis
just need to bring line 4 at
tu
end of the code.
41. Identify the error in the following code ?
1 import csv
2. line [[1, 2,3], [4, 5, 6] ]
3. with open(path, "w", newline =" ") as csv_file :
4. writer [Link](csv_file, delimiter = |')
5. for line in data:
6. [Link] (line)
Solution. The give code is trying to write a nested list with writerow( .
It should be
replaced with writerows( ), i.e., line 6 should be:
[Link](line)
FILE HANDLING
Chopter 5:
245
to read
42 Write a program a text
file and display the count of lowercase and
uppercase letters in the file.
(Note: use text file [Link] given in Fig. 5.5 in the
chapter)
Solution. myfile
ch = "
=

open("[Link]", "r")
lcount 0
#initially stored a space ( a non-None value)
#variable to store count of lowercase letters
ucount= 0

while ch #while ch storesa Non-None value


ch [Link](1) #one character read from f1le
if [Link]() == True:
ucount = ucount +1
else
lcount = lcount + 1

print("Uppercase letters in the file:", ucount)


print("Lowercase letters in the file:", lcount)
# close the file
[Link]()
43. Your recipe uses some ingredients. Write a program to store the list of ingredients in a binaryfie

Solution. import pickle


ingredients = ['cucumber', 'pumpkin', 'carrot', 'peas']
with open('[Link]', 'wb') as fout:
[Link](ingredients, fout)
the
44. Write a method in python to read the content from a text file [Link] line by line and display same on

Outside Delhi 2015)


Screen.
Solution. def read_file () :
inFile open('[Link]', 'r')
for line in inFile:

print(line)
the of the
text file [Link], to find and display
occurrence

45. Write a method in python to read lines from a


(Delhi 2018)
word "India".
INDIA. TXT
growing economy.
"India is the fastest globe.
investments around the
India is looking for more
market.
looking at India as a great
The whole world is India is
foresee the heights that
Most of the Indians can
capable of reaching."

The output should be 4

Solution. def display1( ):


count
'r')
file open( '[Link]',
for LINE in file:
Words [Link]()
for W in Words:
"India":
if W =
cOunt count +1

print ( count)

[Link]()
246 COMPUTER SCIENCE WITH
PYTHONON - X

46. Write a method in python to read lines


from a text file [Link], and display those line
starting with an alphabet 'K". lines, which are
(Outsid Delhi 2017)
Solution.
def display() :
file open(
=
"[Link]', 'r')
line = [Link]()
while line:
if line[e]=='K' :
print (1ine )
line = [Link]()
[Link]()
47. Considering the following definition of dictionary MULTIPLEX, write a method in
display all the content in a pickled file [Link], where MTYPE key of the python to search ond
the value 'Comedy'. dictionary is matching uih
(similar to Delhi 2018)
MULTIPLEX ={'MNO':- 'MNAME' MTYPE':
Solution. def Search ():
file =
open( '[Link]', 'rb')
try:
while True:
MULTIPLEX = [Link](file)
if MULTIPLEX [ 'MTYPE']=="Comedy"
print (MULTIPLEX))
except EOFError:
[Link]()
48. A binaryfile "[Link]" has structure (admission_number, Name, Percentage). Write a
in Python that would read contents function countrec)
of the file "[Link]'" and display the details of those students
whose percentage is above 75. Also display number of students
scoring above 75%. [CBSE SP 2020-21)
Solution.. import pickle
def CountRec() :
fobj = open("[Link]","rb")
num = 0

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

# declare empty dictionary object to hold read records


emp = {}
found = False

#open binary file in read and write mode


fin =open("[Link]', 'rb+")
[Link](e)
# read from the fille
try:
while True
# store file-pointer position before reading the record
rpos [Link]()
# read record in emp dictionary from fin file handle
emp [Link] (fin)
if emp[' Empno'] == 1251
2000 #changes made in the record
emp[ 'Salary'] =emp[ 'Salary'] +

the file-pointer at the exact location of the record


[Link](rpos) #place
[Link](emp, fin) # write the modified record

print(empp)
found True
except EOFError:
if found == False:

print("Sorry, no matching record found. ")


else
print("Record(s) successfully updated.")
# close file
[Link]()
most commonly occurring
word. Also, listthe freguencies of words in the
. ake a sample text file andfind the
text file.
Solution
"r") as fh:
with open ("[Link]",
contents = [Link] ()

wordlist = contents. split()


wordfreq = []

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

while ans == 'y':


print("Record", i
sport= input("Sport name: ")
comp int(input("No. of competitions participated: "))
prizes = int(input( "Prizes won: "))
sport, comp, prizes ] # create sequence of user data
srec [
swriter. writerow(srec)
i = i+1
ans input("Want to enter more records? (y/n).. ")
[Link]()
FILE HANDLING
Chapter 5:
249
Sample run:
Record 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]()

Sample run of the program:


Enter item detail1s
Enter Item code :E01
Enter description :Eraser
Edit Format View Help
Enter price:10 Eile
Item_Name, Description,Price
items? (y/n)...y
Want to enter more E01, Eraser, 10.0
Enter Item code :P11 P11,Pencil,15.e
Enter description :Pencil Res, Ruler, 20.0

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

Type B Application Based Questions


1. How are following codes different from one another ?
(a)my_file open(" [Link]','r')
=

(6) my_file = open("[Link]', 'r')


my [Link]()
my_file.read(100)
Chaprer 5 FILE HANDLING

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 =

Output 1") (d) print("D. Output 4")


(a) print("A.
print ([Link](9))
print([Link]())

print() of Readlines function is")


(e) print("E. Output
(b) print("B. Output2") print([Link] () )
print([Link]() ) print()
print()
c)print("C. Output 3")
print(file1. read (9)) changes
(a), which
means
follows code
print() ie., code (6)
in succession, and (6), and so o n .
Consider the code fragments
Similarly, code (c) follows ()
NOTE. is executing. (b)
intact when code
Dy code (a) remain
6. What is the following
code doing?
open("[Link]",
"a")
file = enter name. ")
input ("Please
phone number. ")
name
enter do?
phno input("Please
code is trying to
"," + phno + "\n") out what
the following
Q. and figure
[Link](name+
above
"[Link]"
created in
Lonsider the file
input("Enter
name :")
name open("[Link]",
"r")
file =
for line in file:
if name in line:
print(line)
252 COMPUTER SCIENCE WITH PVT
8. Consider the file
THON.
[Link] and predict the output of following code fragment. What
following code fragmnent doing ? Nhat exacthy is t
f
open("poemBTH. txt", "r")
nl
for line in f:
nl + 1
print (n1)
9. If you use the code of Q.8 with [Link] (created in solved problem 14), what would be its on
10. Write a method in
on screen.
Python to read the content from a text file [Link] line by line
and displav #
Same
11. Write a method inPython to write multiple line of text contents into a text file
CBSE D2019
12. What will be the [Link] t
output of the following code?
import pickle
ID
{1:"Ziva",2:"53050",3: "IT",4: "38",5: "Dunzo"}
fin open("[Link]", "wb")

[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)

Type C: Programming Practice/Knowledge based Questions


write a program that
reads a text file and creates another file
that is identical
of consecutive blank spaces is replaced by a single space. except that every sequence
A fle [Link] contains information in following format: Event - Participant
Write a function that would read contents from file [Link] and creates a file named [Link]
copying only those records from [Link] where the event name is "Atheletics"
3 A file contains a list of telephone numbers in the following form:
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.
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

As simplified by official websites.


The EUCount() function should display the output as

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.
=

Consider the following definition of dictionary


Staff, write a method in python to search and disnla.. the
15.
is matching with 'S010e
content in a file [Link], where Staffcode key of the dictionary
pickled 105.

Staff { 'Staffcode' Name' (similar to Delhi 2016)


COMPANY, write a method in Python to search and
Considering the following definition of dictionary
-
16.
where ComplD key of the dictionary is matchin
display the content in a pickled file [Link],
with the value '1005'. (similar to Delhi 2017
Company = {'CompID 'CName' 'Turnover'=
17. Write a function in to search and display details of all trains, whose destination is "Delhi" from a binar
file "[Link]". Assuming the binary file is containing the objects of the following dictionary type:

Train { Tno" 'From' To'


18. A binary file "[Link]" has structure [BookNo, Book_Name, Author, Price).
() Write a user defined function CreateFile() to input data for a record and add to [Link].
( Write a function CountRectAuthor) in Python which accepts the Author name as parameter and
count and return number of books by the given Author are stored in the binary file "[Link]"
[CBSE Sample Paper 2020-21
19. Write a function Show_words() in python to read the content of a text file '[Link]' and display
5 words in them.
only such lines of the file which have exactly
Example, if the file contains
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.

Then the function should display the output as:

This is a sample file.


ICBSE 2020C)
The file contains many sentences.
20. Write a Python program to read a given CSV file having tab delimiter.
21. Write a Python program to write a nested Python list to a csv file in one go. After writing the Lvfile
read the CSV file and display the content.
22.
Write function that reads
a a csv file and creates another csv file with the same content, but wa
different delimiter.
23. Write a function that reads a csv file and creates another csv file with the same content exCEpe
beginning with 'check'.

You might also like