Chapter 2: File Handling in Python
Marks: 20
Part A
I. Choose the correct answer. (1 × 3 = 3)
Which file mode is used to append data to an existing file?
a) r
b) w
c) a
d) rb
Which method is used to read all lines of a file and return them as a list?
a) read()
b) readline()
c) readlines()
d) write()
Which module is used for binary file handling in Python?
a) os
b) math
c) pickle
d) random
Part B
II. Fill in the blanks by choosing the appropriate answer from those given in brackets. (1 × 2 = 2)
The default file opening mode in Python is __________.
(a, r, w, rb)
The method used to find the current position of the file pointer is __________.
(read(), seek(), tell(), close())
Part C
III. Answer any THREE of the following. (2 × 3 = 6)
Define a file.
State any two advantages of using files.
Differentiate between Text File and Binary File.
What is the purpose of close() method?
What is the difference between write() and writelines() methods?
Part D
IV. Answer any THREE of the following. (3 × 3 = 9)
Explain any three file open modes used in Python.
Explain the advantages of using the with statement in file handling.
Write a Python program to create a text file and write the string "Computer Science" into it.
Explain the dump() and load() methods of the Pickle module.
Explain seek() and tell() methods with syntax.
Answer Key
Part A
c) a
c) readlines()
c) pickle
Part B
tell()
Part C
A file is a named location on secondary storage used to store data permanently.
Any two:
Permanent storage
Reusability
Sharing
Large data handling
Text File
Binary File
Human readable
Not human readable
Stores characters
Stores raw bytes
Releases system resources.
Flushes buffered data.
Prevents data corruption.
write()
writelines()
Writes one string
Writes multiple strings
Returns character count
Returns None
Part D
Any three modes:
r – Read mode
w – Write mode
a – Append mode
r+ – Read and Write mode
Automatically closes file.
Prevents resource leaks.
Cleaner syntax.
Handles exceptions safely.
Python
f = open("[Link]", "w")
[Link]("Computer Science")
[Link]()
Python
[Link](object, file)
Stores object in binary file.
Python
[Link](file)
Retrieves object from binary file.
Python
[Link]()
Returns current file pointer position.
Python
[Link](offset)
Moves file pointer to a specified location.