0% found this document useful (0 votes)
3 views46 pages

Chapter2 Removed

The document contains multiple choice questions related to file handling in Python, covering topics such as file types, opening and closing files, writing and reading from text files, and the use of the pickle module for serialization. Each question is followed by the correct answer, providing a comprehensive overview of file operations in Python. The content is structured as a study guide for learners to test their knowledge on the subject.

Uploaded by

drkhdlol
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)
3 views46 pages

Chapter2 Removed

The document contains multiple choice questions related to file handling in Python, covering topics such as file types, opening and closing files, writing and reading from text files, and the use of the pickle module for serialization. Each question is followed by the correct answer, providing a comprehensive overview of file operations in Python. The content is structured as a study guide for learners to test their knowledge on the subject.

Uploaded by

drkhdlol
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

CHAPTER2 December 2, 2025

MULTIPLE CHOICE QUESTIONS (MCQ)

1. Introduction to Files

1. What is the primary purpose of storing data in files?

a) To execute programs faster

b) To permanently store data for later access

R
c) To reduce memory usage

L
N
d) To improve program readability
Answer: b) To permanently store data for later access

EE
2. Where are files stored in a computer system?

a) Primary memory (RAM)


H
AT
b) Secondary storage media
M

c) CPU registers
ED

d) Cache memory
Answer: b) Secondary storage media
M
M

2. Types of Files
A

3. Which of the following is a text file extension?


H

a) .txt
O
M

b) .jpg

c) .exe

d) .mp3
Answer: a) .txt

4. What is the main difference between text and binary files?

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
15
CHAPTER2 December 2, 2025

a) Text files are smaller in size

b) Binary files contain human-readable characters

c) Text files consist of ASCII/Unicode characters

d) Binary files cannot be opened in Python


Answer: c) Text files consist of ASCII/Unicode characters

R
5. What happens if a binary file is opened in a text editor?

L
a) It displays the correct content

N
b) It shows garbage values

EE
c) It automatically converts to text

H
AT
d) It asks for a password
Answer: b) It shows garbage values
M

6. Which of the following is an example of a binary file?

a) A .csv file
ED

b) A .py file
M

c) A .docx file
M

d) A .txt file
A

Answer: c) A .docx file


H

7. What is the default EOL character in Python?


O

a) \r
M

b) \n

c) \t

d) \0
Answer: b) \n

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
16
CHAPTER2 December 2, 2025

8. Which encoding scheme is commonly used for text files?

a) ASCII

b) JPEG

c) MPEG

R
d) ZIP
Answer: a) ASCII

L
N
EE
3. Opening and Closing Files

9. Which function is used to open a file in Python?


H
AT
a) file_open()

b) open()
M

c) load()
ED

d) read()
Answer: b) open()
M

10. What is the default mode for opening a file?


M

a) Read mode (‘r’)


A

b) Write mode (‘w’)


H
O

c) Append mode (‘a’)


M

d) Binary mode (‘b’)


Answer: a) Read mode (‘r’)

11. Which mode is used to open a file for both reading and writing?

a) ‘r’

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
17
CHAPTER2 December 2, 2025

b) ‘w+’

c) ‘a’

d) ‘b’
Answer: b) ‘w+’

12. What happens if a file opened in ‘w’ mode already exists?

R
a) The file is opened in read mode

L
b) The existing content is overwritten

N
c) The file is deleted

EE
d) An error occurs
Answer: b) The existing content is overwritten
H
AT
13. Which attribute returns the access mode of a file?

a) [Link]
M

b) [Link]
ED

c) [Link]
M

d) [Link]
M

Answer: b) [Link]

14. How is a file closed in Python?


A
H

a) [Link]()
O

b) close(file)
M

c) [Link]()

d) exit(file)
Answer: a) [Link]()

15. What is the advantage of using the with clause to open a file?

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
18
CHAPTER2 December 2, 2025

a) It allows faster file operations

b) It automatically closes the file

c) It encrypts the file

d) It compresses the file


Answer: b) It automatically closes the file

R
L
N
4. Writing to a Text File

EE
16. Which method is used to write a single string to a file?

a) writeline()
H
AT
b) write()
M

c) append()

d) insert()
ED

Answer: b) write()

17. What does the write() method return?


M

a) The number of characters written


M

b) The file object


A
H

c) The content of the file


O

d) None
M

Answer: a) The number of characters written

18. How can numeric data be written to a text file?

a) Directly using write()

b) By converting it to a string first

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
19
CHAPTER2 December 2, 2025

c) Using the dump() method

d) It cannot be written
Answer: b) By converting it to a string first

19. Which method is used to write multiple strings to a file?

a) writelines()

R
b) write()

L
c) appendlines()

N
d) insertlines()

EE
Answer: a) writelines()

20. What is the purpose of the flush() method?


H
AT
a) To close the file

b) To clear the buffer and write contents to the file


M

c) To read the file


ED

d) To delete the file


Answer: b) To clear the buffer and write contents to the file
M
M
A

5. Reading from a Text File


H

21. Which method reads a specified number of bytes from a file?


O

a) read()
M

b) readline()

c) readlines()

d) seek()
Answer: a) read()

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
20
CHAPTER2 December 2, 2025

22. What happens if no argument is passed to the read() method?

a) It reads one line

b) It reads the entire file

c) It returns an error

R
d) It reads 10 bytes
Answer: b) It reads the entire file

L
23. Which method reads one complete line from a file?

N
a) read()

EE
b) readline()

c) readlines() H
AT
d) load()
M

Answer: b) readline()

24. What does the readlines() method return?


ED

a) A single string
M

b) A list of strings
M

c) A tuple of strings
A

d) A dictionary of strings
H

Answer: b) A list of strings


O

25. How can you read a file line by line using a loop?
M

a) Using readline() in a while loop

b) Using read() in a for loop

c) Using seek() in a loop

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
21
CHAPTER2 December 2, 2025

d) Using dump() in a loop


Answer: a) Using readline() in a while loop

26. What does the split() function do when reading a file?

a) Splits the file into multiple files

b) Splits each line into a list of words

R
c) Joins multiple lines

L
d) Closes the file

N
Answer: b) Splits each line into a list of words

EE
6. Setting Offsets in a File H
AT
27. Which method returns the current position of the file object?
M

a) seek()

b) tell()
ED

c) pos()
M

d) offset()
M

Answer: b) tell()
A

28. What is the purpose of the seek() method?


H

a) To close the file


O

b) To move the file object to a specific position


M

c) To read the file

d) To write to the file


Answer: b) To move the file object to a specific position

29. What is the default reference point for the seek() method?

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
22
CHAPTER2 December 2, 2025

a) Beginning of the file (0)

b) Current position (1)

c) End of the file (2)

d) Middle of the file


Answer: a) Beginning of the file (0)

R
30. How do you move the file object to the 10th byte from the beginning?

L
a) seek(10, 0)

N
b) seek(0, 10)

EE
c) seek(10, 1)

H
AT
d) seek(10, 2)
Answer: a) seek(10, 0)
M
ED

7. Creating and Traversing a Text File

31. What happens if a file opened in ‘a’ mode does not exist?
M

a) An error occurs
M

b) A new file is created


A
H

c) The file is deleted


O

d) The file is opened in read mode


M

Answer: b) A new file is created

32. Which mode is used to open a file for both reading and writing without overwriting existing content?

a) ‘r+’

b) ‘w+’

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
23
CHAPTER2 December 2, 2025

c) ‘a+’

d) ‘b+’
Answer: c) ‘a+’

33. How can you iterate over all lines in a file?

a) Using a for loop on the file object

R
b) Using a while loop with readline()

L
c) Both a and b

N
d) Using seek()

EE
Answer: c) Both a and b

H
34. What is the output of [Link]() after writing data to a file?
AT
a) The number of lines written

b) The current byte position of the file object


M

c) The file size


ED

d) The number of characters written


Answer: b) The current byte position of the file object
M
M
A

8. The Pickle Module


H

35. What is the purpose of the pickle module?


O

a) To read text files


M

b) To serialize and deserialize Python objects

c) To write binary files

d) To compress files
Answer: b) To serialize and deserialize Python objects

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
24
CHAPTER2 December 2, 2025

36. Which method is used to write Python objects to a binary file?

a) write()

b) dump()

c) load()

R
d) pickle()
Answer: b) dump()

L
37. Which method is used to read Python objects from a binary file?

N
a) read()

EE
b) load()

c) get() H
AT
d) unpickle()
M

Answer: b) load()

38. What mode is used to open a binary file for writing?


ED

a) ‘w’
M

b) ‘wb’
M

c) ‘wr’
A

d) ‘w+’
H

Answer: b) ‘wb’
O

39. What happens if a binary file is corrupted?


M

a) It can be easily fixed

b) It becomes unreadable

c) It automatically repairs itself

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
25
CHAPTER2 December 2, 2025

d) It converts to a text file


Answer: b) It becomes unreadable

40. Which exception is raised when the end of a binary file is reached during unpickling?

a) FileNotFoundError

b) EOFError

R
c) IOError

L
d) ValueError

N
Answer: b) EOFError

EE
Miscellaneous H
AT
41. What is serialization?
M

a) Converting Python objects to byte streams

b) Reading text files


ED

c) Writing binary files


M

d) Closing files
M

Answer: a) Converting Python objects to byte streams


A

42. What is deserialization?


H

a) Converting byte streams to Python objects


O

b) Writing text files


M

c) Reading binary files

d) Opening files
Answer: a) Converting byte streams to Python objects

43. Which module is required for pickling and unpickling?

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
26
CHAPTER2 December 2, 2025

a) io

b) pickle

c) os

d) sys
Answer: b) pickle

R
44. What is the output of [Link] if the file is open?

L
a) True

N
b) False

EE
c) 1

H
AT
d) 0
Answer: b) False
M

45. Which method is used to forcefully write buffer contents to a file?

a) close()
ED

b) flush()
M

c) write()
M

d) dump()
A

Answer: b) flush()
H

46. What is the purpose of the splitlines() method?


O

a) To split a file into multiple files


M

b) To split a string into a list of lines

c) To join lines in a file

d) To close a file
Answer: b) To split a string into a list of lines

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
27
CHAPTER2 December 2, 2025

47. Which of the following is not a file attribute?

a) [Link]

b) [Link]

c) [Link]

R
d) [Link]
Answer: c) [Link]

L
48. What is the correct way to open a file for reading and writing in binary mode?

N
a) open(“[Link]”, “r+b”)

EE
b) open(“[Link]”, “rwb”)

c) open(“[Link]”, “br+”) H
AT
d) open(“[Link]”, “b+r”)
M

Answer: a) open(“[Link]”, “r+b”)

49. What is the correct syntax for the with clause?


ED

a) with open(“[Link]”, “r”) as f:


M

b) with open(“[Link]”, “r”) -> f:


M

c) with open(“[Link]”, “r”) in f:


A

d) with open(“[Link]”, “r”) f:


H

Answer: a) with open(“[Link]”, “r”) as f:


O

50. What is the purpose of the io module in Python?


M

a) To handle file operations

b) To perform mathematical calculations

c) To create graphical interfaces

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
28
CHAPTER2 December 2, 2025

d) To connect to databases
Answer: a) To handle file operations

51. Assertion (A): A text file can be opened and read using a text editor.
Reason (R): Text files store data in the form of ASCII or Unicode characters.

Options:
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A

R
(C) A is true, but R is false
(D) A is false, but R is true

L
N
Answer: A

EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
29
CHAPTER2 December 2, 2025

56.
As-
ser-
tion
(A):

R
The
writelines()

L
method
re-

N
quires

EE
a list
or
tuple
of
H
AT
strings.
Rea-
M

son
(R):
It
ED

adds
new-
M

line
char-
M

ac-
ters
A

be-
H

tween
O

each
string
M

auto-
mati-
cally.

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
30
CHAPTER2 December 2, 2025

Options:
(A)
Both
A
and

R
R are
true,

L
and
R is

N
the

EE
cor-
rect
ex-
pla-
H
AT
na-
tion
M

of A
(B)
Both
ED

A
and
M

R are
true,
M

but R
is not
A

the
H

cor-
O

rect
ex-
M

pla-
na-
tion
of A
(C) A
is
true,
but R
is
false
L R MOHAMMED MATHEEN (D) AM.C.A., M.A., [Link]., UGC NET.,
LECTURER, PRIMUS PU is
COLLEGE, BANGALORE - 560 035
31

false,
but R
CHAPTER2 December 2, 2025

Answer:
C

57. Assertion (A): Opening a file in 'w' mode erases its existing contents.
Reason (R): In this mode, the file pointer is placed at the end of the file.

R
Options:

L
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A

N
(C) A is true, but R is false

EE
(D) A is false, but R is true

Answer: C
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
32
CHAPTER2 December 2, 2025

60.
As-
ser-
tion
(A):

R
The
readlines()

L
method
re-

N
turns

EE
a list
con-
tain-
ing
H
AT
each
line
M

as an
ele-
ment.
ED

Rea-
son
M

(R):
This
M

method
is
A

use-
H

ful
O

when
we
M

want
to it-
erate
through
lines
as list
ele-
ments.

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
33
CHAPTER2 December 2, 2025

Options:
(A)
Both
A
and

R
R are
true,

L
and
R is

N
the

EE
cor-
rect
ex-
pla-
H
AT
na-
tion
M

of A
(B)
Both
ED

A
and
M

R are
true,
M

but R
is not
A

the
H

cor-
O

rect
ex-
M

pla-
na-
tion
of A
(C) A
is
true,
but R
is
false
L R MOHAMMED MATHEEN (D) AM.C.A., M.A., [Link]., UGC NET.,
LECTURER, PRIMUS PU is
COLLEGE, BANGALORE - 560 035
34

false,
but R
CHAPTER2 December 2, 2025

Answer:
A

R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
35
CHAPTER2 December 2, 2025

61.
As-
ser-
tion
(A):

R
The
tell()

L
func-
tion

N
re-

EE
turns
the
cur-
rent
H
AT
byte
posi-
M

tion
of the
file
ED

ob-
ject.
M

Rea-
son
M

(R):
It is
A

help-
H

ful
O

when
track-
M

ing
file
offset
dur-
ing
file
oper-
a-
tions.

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
36
CHAPTER2 December 2, 2025

Options:
(A)
Both
A
and

R
R are
true,

L
and
R is

N
the

EE
cor-
rect
ex-
pla-
H
AT
na-
tion
M

of A
(B)
Both
ED

A
and
M

R are
true,
M

but R
is not
A

the
H

cor-
O

rect
ex-
M

pla-
na-
tion
of A
(C) A
is
true,
but R
is
false
L R MOHAMMED MATHEEN (D) AM.C.A., M.A., [Link]., UGC NET.,
LECTURER, PRIMUS PU is
COLLEGE, BANGALORE - 560 035
37

false,
but R
CHAPTER2 December 2, 2025

Answer:
A

62. Assertion (A): The seek() method is used to randomly access a file.
Reason (R): It always moves the file pointer to the beginning of the file.

R
Options:
(A) Both A and R are true, and R is the correct explanation of A

L
(B) Both A and R are true, but R is not the correct explanation of A

N
(C) A is true, but R is false
(D) A is false, but R is true

EE
Answer: C

H
63. Assertion (A): The with statement is preferred in Python for file handling.
AT
Reason (R): It automatically closes the file when execution goes out of scope.
M

Options:
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A
ED

(C) A is true, but R is false


(D) A is false, but R is true
M

Answer: A
M

64. Assertion (A): Pickling converts a Python object into a byte stream.
A

Reason (R): It is useful for storing Python objects in binary files.


H

Options:
O

(A) Both A and R are true, and R is the correct explanation of A


(B) Both A and R are true, but R is not the correct explanation of A
M

(C) A is true, but R is false


(D) A is false, but R is true

Answer: A

65. Assertion (A): The dump() method writes binary data to a file.
Reason (R): The file must be opened in 'rb' mode to use dump().

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
38
CHAPTER2 December 2, 2025

Options:
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A
(C) A is true, but R is false
(D) A is false, but R is true

Answer: C

R
(dump() requires 'wb', not 'rb')

66. Assertion (A): The load() method is used for unpickling data from a binary file.

L
Reason (R): It recreates the original Python object from the byte stream.

N
Options:

EE
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A
(C) A is true, but R is false
(D) A is false, but R is true H
AT
Answer: A
M

67. Assertion (A): All Python objects can be pickled.


ED

Reason (R): The pickle module can serialize even open file objects and sockets.

Options:
M

(A) Both A and R are true, and R is the correct explanation of A


(B) Both A and R are true, but R is not the correct explanation of A
M

(C) A is true, but R is false


(D) A is false, but R is true
A
H

Answer: D
O

(Not all objects can be pickled – open files, sockets, etc., cannot be.)
M

68. Assertion (A): A file opened using mode 'a+' allows both appending and reading.
Reason (R): The file pointer is initially placed at the beginning of the file.

Options:
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A
(C) A is true, but R is false

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
39
CHAPTER2 December 2, 2025

(D) A is false, but R is true

Answer: C
(In 'a+', pointer is at the end, not beginning.)

R
69. Assertion (A): If a file opened using 'w' mode does not exist, it will be created.
Reason (R): The 'w' mode only works on already existing files.

L
Options:

N
(A) Both A and R are true, and R is the correct explanation of A
(B) Both A and R are true, but R is not the correct explanation of A

EE
(C) A is true, but R is false
(D) A is false, but R is true

H
AT
Answer: C

70. Assertion (A): [Link]() raises EOFError when end of file is reached.
M

Reason (R): This helps to read binary files using a while loop and try-except block.

Options:
ED

(A) Both A and R are true, and R is the correct explanation of A


(B) Both A and R are true, but R is not the correct explanation of A
M

(C) A is true, but R is false


(D) A is false, but R is true
M
A

Answer: A
H

FILL IN THE BLANKS


O
M

1. A file is a named location on ________ storage media where data is permanently stored. Answer:
secondary

2. The two main types of files are ________ files and binary files. Answer: text

3. Text files store data using ________ or Unicode encoding schemes. Answer: ASCII

4. The default End of Line (EOL) character in Python is ________. Answer: \n

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
40
CHAPTER2 December 2, 2025

5. Binary files store data in ________ format that is not human-readable. Answer: byte

6. The ________ function is used to open a file in Python. Answer: open()

7. The default file opening mode is ________. Answer: ‘r’ (read mode)

8. To open a file for both reading and writing, we use ________ mode. Answer: ‘r+’

9. The ________ method returns the current position of the file pointer. Answer: tell()

10. To move the file pointer to a specific position, we use the ________ method. Answer: seek()

R
11. The ________ clause automatically closes the file when the block ends. Answer: with

L
12. The ________ method writes a single string to a file. Answer: write()

N
13. The ________ method writes multiple strings from an iterable to a file. Answer: writelines()

EE
14. To read a specified number of bytes from a file, we use the ________ method. Answer: read()

15. The ________ method reads one complete line from a file. Answer: readline()

H
16. The ________ method reads all lines and returns them as a list. Answer: readlines()
AT
17. The ________ module is used for serializing and deserializing Python objects. Answer: pickle

18. The ________ method converts Python objects to byte streams for storage. Answer: dump()
M

19. The ________ method loads Python objects from binary files. Answer: load()
ED

20. Files opened in ________ mode will overwrite existing content. Answer: ‘w’

21. The ________ mode allows appending data to the end of an existing file. Answer: ‘a’
M

22. The ________ attribute returns True if a file is closed. Answer: closed
M

23. The ________ attribute returns the name of the file. Answer: name

24. The ________ method forces writing of buffered data to the file. Answer: flush()
A

25. To handle non-text data like images, we open files in ________ mode. Answer: binary (‘b’)
H

26. The ________ exception occurs when trying to read past EOF in pickle. Answer: EOFError
O

27. The ________ method splits strings at whitespace by default. Answer: split()
M

28. The ________ method splits strings at line boundaries. Answer: splitlines()

29. In file operations, ________ refers to converting objects to byte streams. Answer: serialization

30. The ________ function converts numbers to strings before file writing. Answer: str()

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
41
CHAPTER2 December 2, 2025

2 MARKS QUESTIONS

1. Differentiate between text files and binary files.


Answer:

• Text files store data as human-readable characters (ASCII/Unicode) with extensions like .txt,
.py.

R
• Binary files store data as bytes (0s/1s) for non-text data like images/audio with extensions
like .dat, .jpg.

L
N
2. What is the purpose of file modes? Give syntax to open a file in read-write mode.

EE
Answer:
File modes determine operations allowed on a file.
Syntax: file_object = open("[Link]", "r+")

H
AT
3. Explain the difference between write() and writelines() methods with examples.
Answer:
M

• write(): Writes a single string ([Link]("Hello"))


ED

• writelines(): Writes a list of strings ([Link](["Line1\n", "Line2"]))


M

4. What happens when a file is opened in ‘w’ mode versus ‘a’ mode?
Answer:
M

• ‘w’ mode overwrites existing content.


A
H

• ‘a’ mode appends to existing content.


O
M

5. Give the syntax and purpose of seek() and tell() methods.


Answer:

• tell(): Returns current position (pos = [Link]())

• seek(offset, reference_point): Moves pointer (e.g., [Link](5, 0) moves to


5th byte from start).

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
42
CHAPTER2 December 2, 2025

6. Differentiate between read(), readline(), and readlines() methods.


Answer:

• read(): Reads entire file or specified bytes.

• readline(): Reads one line.

• readlines(): Returns all lines as a list.

R
L
7. Why is closing files important? Show two ways to close a file.
Answer:

N
Prevents memory leaks and ensures data is saved.

EE
Methods:

1. Explicit: [Link]()

2. Implicit: Using with open() as file: H


AT
M

8. What is pickling? Give syntax to dump a Python list into a binary file.
Answer:
Pickling converts Python objects to byte streams.
ED

Syntax:

import pickle
M

[Link]([1, 2, 3], open("[Link]", "wb"))


M

9. Explain the purpose of the split() method in file handling with an example.
Answer:
A

Splits strings into lists.


H

Example:
O

line = "Hello World"


words = [Link]() # Returns ['Hello', 'World']
M

10. How does the ‘with’ statement improve file handling?


Answer:
Automatically closes files after block execution, even if errors occur.

11. Differentiate between ‘r+’ and ‘w+’ file modes.


Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
43
CHAPTER2 December 2, 2025

• ‘r+’: Opens for read/write (file must exist).

• ‘w+’: Opens for read/write (creates/overwrites file).

12. What is serialization? Name the Python module used for it.
Answer:
Process of converting objects to byte streams. Module: pickle.

R
13. Give syntax to load data from a binary file using pickle.

L
Answer:

N
data = [Link](open("[Link]", "rb"))

EE
14. What happens if you open a non-existent file in ‘r’ mode versus ‘w’ mode?
Answer:

• ‘r’ mode raises FileNotFoundError.


H
AT
• ‘w’ mode creates a new file.
M

15. Explain the role of file offsets with an example of seek().


ED

Answer:
File offsets indicate byte positions.
Example: [Link](10) moves pointer to 10th byte.
M
M

16. How does append mode (‘a’) differ from write mode (‘w’) in file handling?
Answer:
A

• ‘a’ preserves existing content and adds new data at the end.
H
O

• ‘w’ deletes existing content.


M

17. What is the significance of the flush() method?


Answer:
Forces immediate writing of buffered data to the file.

18. Give an example to demonstrate reading a file line by line.


Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
44
CHAPTER2 December 2, 2025

with open("[Link]", "r") as f:


for line in f:
print(line)

19. What are the attributes of a file object? Mention any two.
Answer:

• [Link]: Returns filename.

R
• [Link]: Returns access mode.

L
20. Differentiate between dump() and load() methods of the pickle module.

N
Answer:

EE
• dump(): Writes objects to binary files.

• load(): Reads objects from binary files.


H
AT
M

3 MARKS QUESTIONS
ED

1. Explain the file handling process in Python with proper steps. Answer:

• Open file using open() function with filename and mode


M

• Perform operations (read/write) using appropriate methods


• Close file using close() method to free resources
M

• Alternatively use with statement for automatic closing


A

2. Differentiate between text and binary files with three points each. Answer: Text Files:
H

• Store human-readable characters


O

• Use ASCII/Unicode encoding


• Extensions: .txt, .py, .csv
M

Binary Files:

• Store data as bytes (0s/1s)


• Non-human readable format
• Extensions: .dat, .jpg, .mp3

3. Explain any three file opening modes with examples. Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
45
CHAPTER2 December 2, 2025

• 'r': Read mode (default) - open("[Link]", "r")


• 'w': Write mode (overwrites) - open("[Link]", "w")
• 'a': Append mode - open("[Link]", "a")

4. Write a Python program to create a file and write three lines of text to it.

Answer: python with open("[Link]", "w") as f: [Link]("First


line\n") [Link]("Second line\n") [Link]("Third line\n")

R
6. Explain the working of seek() and tell() methods with examples. Answer:

L
• tell(): Returns current position
pos = [Link]() # Returns byte position

N
• seek(): Moves file pointer

EE
[Link](5) # Moves to 5th byte
[Link](0, 2) # Moves to end of file

H
7. Differentiate between read(), readline() and readlines() methods. Answer:
AT
• read(): Reads entire content or specified bytes
• readline(): Reads single line
M

• readlines(): Returns list of all lines


ED

8. Explain the pickle module with its two main methods and syntax. Answer:

• Used for object serialization


M

• dump(): Writes object to file


[Link](obj, file)
M

• load(): Reads object from file


A

obj = [Link](file)
H

9. Write a program to read a file and display lines starting with ‘A’.
O

Answer:
M

with open("[Link]", "r") as f:


for line in f:
if [Link]('A'):
print(line)

10. Explain three advantages of using ‘with’ statement for file handling. Answer:

• Automatically closes file

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
46
CHAPTER2 December 2, 2025

• Handles exceptions properly


• Cleaner and more readable code

11. Differentiate between write() and writelines() methods with examples. Answer:

• write(): Accepts single string


[Link]("Hello")

• writelines(): Accepts sequence of strings

R
[Link](["Line1", "Line2"])

L
12. Explain the concept of serialization and deserialization in Python. Answer:

N
• Serialization: Converting object to byte stream (pickling)

EE
• Deserialization: Converting byte stream back to object (unpickling)
• Done using pickle module

H
13. Write a program to copy contents from one file to another.
AT
Answer:

with open("[Link]", "r") as src, open("[Link]", "w") as dest:


M

[Link]([Link]())

14. Explain the file object attributes with examples. Answer:


ED

• [Link]: Returns filename


M

print([Link])

• [Link]: Returns access mode


M

print([Link])
A

• [Link]: Returns True if closed


H

print([Link])
O

15. What are the different reference points in seek() method? Explain. Answer:
M

• 0: Beginning of file (default)


• 1: Current position
• 2: End of file Example: [Link](5, 0) moves to 5th byte from start

16. Write a program to count number of lines in a file.

Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
47
CHAPTER2 December 2, 2025

count = 0
with open("[Link]", "r") as f:
for line in f:
count += 1
print("Total lines:", count)

17. Explain the importance of closing files after operations. Answer:

• Frees system resources

R
• Ensures all data is written
• Prevents data corruption

L
• Releases file locks

N
18. Differentiate between ‘r+’, ‘w+’ and ‘a+’ file modes. Answer:

EE
• 'r+': Read/write (file must exist)
• 'w+': Read/write (creates/overwrites)
• 'a+': Read/append (creates if doesn’t exist)
H
AT
19. Write a program to display the size of a file.

Answer:
M

import os
size = [Link]("[Link]")
ED

print("File size:", size, "bytes")

20. Explain the working of split() and splitlines() methods with examples. Answer:
M

• split(): Splits at whitespace


M

words = "Hello World".split() # ['Hello', 'World']


A

• splitlines(): Splits at line breaks


H

lines = "Line1\nLine2".splitlines() # ['Line1', 'Line2']


O

21. Write a program to create a binary file and store a dictionary in it.
M

Answer:

import pickle
data = {"name": "John", "age": 25}
with open("[Link]", "wb") as f:
[Link](data, f)

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
48
CHAPTER2 December 2, 2025

5 MARKS QUESTIONS

1. Explain the complete file handling process in Python with proper syntax and examples for
each step. Answer:

• Opening: file = open("[Link]", "r") or with open("[Link]", "w")


as file:
• Writing: [Link]("Content") or [Link](["Line1\n", "Line2\n"])

R
• Reading: content = [Link]() or lines = [Link]()
• Positioning: pos = [Link]() and [Link](offset)

L
• Closing: [Link]() (automatic in with statement) Example:

N
with open("[Link]", "w+") as f:
[Link]("Sample text\n")

EE
[Link](0)
print([Link]())

H
2. Compare and contrast text files and binary files with respect to: storage format, readability,
AT
extensions, and use cases. Answer:

• Storage Format: Text uses ASCII/Unicode; Binary uses raw bytes


M

• Readability: Text is human-readable; Binary requires special programs


• Extensions: Text (.txt, .py); Binary (.dat, .jpg)
ED

• Use Cases: Text for configuration/data; Binary for media/executables


• Example:
M

# Text file operation


with open("[Link]", "w") as f:
M

[Link]("Hello")
A

# Binary file operation


H

with open("[Link]", "wb") as f:


[Link](b'\x48\x65\x6c\x6c\x6f')
O

3. Explain in detail the various file opening modes with their file pointer positions and suitable
M

use cases. Answer:

Mode Pointer Position Use Case

‘r’ Beginning Read existing files


‘w’ Beginning Create/overwrite files

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
49
CHAPTER2 December 2, 2025

Mode Pointer Position Use Case

‘a’ End Append to existing files


‘r+’ Beginning Read/write existing files
‘w+’ Beginning Create/overwrite with read capability
‘a+’ End Append with read capability

R
‘b’ - Binary mode suffix (e.g., ‘rb’, ‘wb’)

L
4. Demonstrate the complete process of pickling and unpickling with proper error handling.

N
Answer:

EE
import pickle

# Pickling (Serialization)
try:
data = {"name": "Alice", "age": 25} H
AT
with open("[Link]", "wb") as f:
[Link](data, f)
M

except [Link]:
print("Error in pickling data")
ED

# Unpickling (Deserialization)
try:
with open("[Link]", "rb") as f:
M

loaded = [Link](f)
print(loaded)
M

except ([Link], EOFError):


print("Error in unpickling data")
A
H

5. Explain the file object attributes and methods with suitable examples for each. Answer:
O

• Attributes:
– name: print([Link]) # Shows filename
M

– mode: print([Link]) # Shows access mode


– closed: print([Link]) # True/False
• Methods:
– read(): content = [Link](10) # First 10 bytes
– seek(): [Link](5) # Move to 5th byte
– tell(): pos = [Link]() # Current position

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
50
CHAPTER2 December 2, 2025

– flush(): [Link]() # Force write to disk

6. Develop a complete Python program to maintain student records in a file with the following
operations: add, view, and search records. Answer:

def add_student():
with open("[Link]", "a") as f:
name = input("Enter name: ")
roll = input("Enter roll no: ")

R
[Link](f"{roll},{name}\n")

L
def view_students():
with open("[Link]", "r") as f:

N
print("\nStudent Records:")
for line in f:

EE
roll, name = [Link]().split(',')
print(f"Roll: {roll}, Name: {name}")

def search_student(): H
AT
roll = input("Enter roll no to search: ")
with open("[Link]", "r") as f:
for line in f:
M

if [Link](roll):
print("Record found:", line)
ED

return
print("Record not found")
M

7. Compare the sequential and random access methods in file handling with appropriate exam-
ples. Answer:
M

• Sequential Access:
A

– Reads/writes in order
H

– Methods: read(), readline(), write()


– Example:
O

with open("[Link]", "r") as f:


M

while True:
line = [Link]()
if not line: break
print(line)
• Random Access:
– Direct access using positions
– Methods: seek(), tell()

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
51
CHAPTER2 December 2, 2025

– Example:
with open("[Link]", "rb+") as f:
[Link](10)
[Link](b"NEWDATA")
print("Current position:", [Link]())

8. Explain the concept of serialization with its advantages and demonstrate using the pickle
module. Answer:

R
• Concept: Converting objects to byte stream for storage/transmission

L
• Advantages:

N
1. Preserves object state
2. Enables complex data storage

EE
3. Supports network transmission

• Example:
import pickle H
AT
# Serialization
data = {"a": [1,2,3], "b": ("hello",), "c": {"key": "value"}}
M

with open("[Link]", "wb") as f:


[Link](data, f)
ED

# Deserialization
with open("[Link]", "rb") as f:
M

loaded = [Link](f)
print(loaded)
M

9. Develop a complete file handling program that demonstrates reading, writing, and appending
A

operations with proper exception handling. Answer:


H

try:
# Writing
O

with open("[Link]", "w") as f:


M

[Link]("Initial content\n")

# Appending
with open("[Link]", "a") as f:
[Link]("Appended content\n")

# Reading
with open("[Link]", "r") as f:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
52
CHAPTER2 December 2, 2025

print("File content:")
print([Link]())

except IOError as e:
print(f"File error: {e}")
except Exception as e:
print(f"Error: {e}")

10. Explain the various techniques for reading file content in Python with examples of when each

R
would be appropriate. Answer:

L
• read(): When you need the entire content as single string

N
with open("[Link]", "r") as f:
content = [Link]() # For small files

EE
• readline(): When processing large files line by line
with open("[Link]", "r") as f:
while True:
H
AT
line = [Link]()
if not line: break
process(line)
M

• readlines(): When you need all lines as a list


ED

with open("[Link]", "r") as f:


lines = [Link]() # For line-based operations

• Iteration: Memory efficient for large files


M

with open("[Link]", "r") as f:


M

for line in f: # No memory overload


process(line)
A

11. Create a comprehensive program that demonstrates all file object methods (read, write,
H

seek, tell, flush) with proper documentation.


O

Answer:
M

# Demonstrate all key file methods


with open("demo_methods.txt", "w+") as f: # Open in write/read mode
# WRITE
[Link]("Line 1\nLine 2\nLine 3\n")
print(f"Initial write - Position: {[Link]()}") # Should show 18 bytes

# FLUSH

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
53
CHAPTER2 December 2, 2025

[Link]() # Force write to disk

# SEEK
[Link](0) # Rewind to start
print(f"After seek(0) - Position: {[Link]()}") # 0

# READ
content = [Link](10) # First 10 chars
print(f"Partial read: {content}")

R
print(f"After read(10) - Position: {[Link]()}") # 10

L
# READLINE

N
[Link](0)
print("Full content:")

EE
while True:
line = [Link]()
if not line: break
print([Link]())
H
AT
12. Compare and contrast the working of text mode vs binary mode file operations with suitable
examples for each.
M

Answer:
ED

Aspect Text Mode Binary Mode

Data Handling Automatic encoding/decoding Raw bytes


M

Newlines Converts \n to OS format No conversion


M

Example Write [Link]("Hello") [Link](b"Hello")


Example Read text = [Link]() data = [Link]()
A

Use Case Config files, logs Images, serialized data


H
O

13. Explain the detailed working of the seek() method with all possible reference points and
M

practical applications.
Answer:

• Reference Points:

1. 0 (default): Beginning of file

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
54
CHAPTER2 December 2, 2025

2. 1: Current position

3. 2: End of file

• Applications:
# Jump to beginning
[Link](0)

R
# Move 5 bytes forward from current position

L
[Link](5, 1)

N
# Go to 10 bytes before end

EE
[Link](-10, 2)

# Practical use: Read last line


[Link](-100, 2) # Move near end
last_line = [Link]()[-1] H
AT
14. Develop a program that demonstrates reading a binary file (like an image) and creating its
copy.
M

Answer:
ED

def copy_binary_file(source, dest):


CHUNK_SIZE = 4096 # 4KB chunks
M

with open(source, "rb") as src, open(dest, "wb") as dst:


while True:
M

chunk = [Link](CHUNK_SIZE)
if not chunk: break
A

[Link](chunk)
H

# Usage
O

copy_binary_file("[Link]", "[Link]")
M

CHAPTER END EXERCISES

1. Differentiate between:
a) Text file and binary file
Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
55
CHAPTER2 December 2, 2025

• Text files store data as human-readable characters (ASCII/Unicode) with extensions like .txt, .py.

• Binary files store data as bytes (0s/1s) for non-text data like images/audio with extensions like
.dat, .jpg.

b) readline() and readlines() Answer:

R
• readline() reads a single line including newline character.

L
• readlines() returns all lines as a list of strings.

N
EE
c) write() and writelines()
Answer:

H
AT
• write() accepts a single string argument.

• writelines() accepts an iterable of strings.


M

2. Write the use and syntax for the following methods:


ED

a) open()
Answer:
M
M

• Use: To open a file


A

• Syntax: file_object = open(filename, mode)


H
O

b) read()
M

Answer:
- Use: Reads file content
- Syntax: content = file_object.read([size])

c) seek()
Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
56
CHAPTER2 December 2, 2025

• Use: Moves file pointer

• Syntax: file_object.seek(offset[, reference_point])

d) dump()
Answer:

R
• Use: Writes Python objects to binary files

L
• Syntax: [Link](object, file_object)

N
EE
3. Write the file mode that will be used for opening the following files. Also, write the
Python statements to open the following files:
H
AT
a) A text file “[Link]” in both read and write mode
Answer:
M

• Mode: 'r+'
ED

• Statement: file = open("[Link]", "r+")


M

b) A binary file “[Link]” in write mode


M

Answer:
A

• Mode: 'wb'
H
O

• Statement: file = open("[Link]", "wb")


M

c) A text file “[Link]” in append and read mode


Answer:

• Mode: 'a+'

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
57
CHAPTER2 December 2, 2025

• Statement: file = open("[Link]", "a+")

d) A binary file “[Link]” in read only mode


Answer:

• Mode: 'rb'

R
• Statement: file = open("[Link]", "rb")

L
4. Why is it advised to close a file after we are done with the read and write operations?

N
What will happen if we do not close it? Will some error message be flashed? Answer:

EE
- Prevents memory leaks and data corruption.
- Unclosed files may remain locked, preventing other operations.
- No immediate error, but may cause resource issues.

H
AT
5. What is the difference between the following set of statements (a) and (b):
a)
M

P = open("[Link]","r")
[Link](10)
ED

b)
with open("[Link]","r") as P:
M

x = [Link]()
M

Answer:
- (a) Requires manual closing ([Link]()).
A

- (b) Automatically closes file after block.


H

6. Write a command(s) to write the following lines to the text file named [Link]. Assume
O

that the file is opened in append mode. “Welcome my class”


M

“It is a fun place”


“You will learn and play”
Answer:
with open("[Link]", "a") as f:
[Link]("Welcome my class\n")
[Link]("It is a fun place\n")
[Link]("You will learn and play\n")

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
58
CHAPTER2 December 2, 2025

7. Write a Python program to open the file [Link] used in question no 6 in read mode
to display its contents. What will be the difference if the file was opened in write mode
instead of append mode? Answer:

# Read mode
with open("[Link]", "r") as f:
print([Link]())

# Write mode would overwrite all content

R
L
8. Write a program to accept string/sentences from the user till the user enters “END”.
Save the data in a text file and then display only those sentences which begin with an

N
uppercase alphabet. Answer:

EE
with open("[Link]", "w") as f:
while True:
line = input("Enter sentence (END to stop): ")
if line == "END": break H
AT
[Link](line + "\n")

# Display filtered content


M

with open("[Link]", "r") as f:


for line in f:
ED

if [Link]() and line[0].isupper():


print([Link]())
M

9. Define pickling in Python. Explain serialization and deserialization of Python object.


M

Answer:
- Pickling: Process of converting Python objects to byte streams.
A

- Serialization: Object → Byte stream (using [Link]()).


H

- Deserialization: Byte stream → Object (using [Link]()).


O

10. Write a program to enter the following records in a binary file: Item No (integer)
M

Item_Name (string)
Qty (integer)
Price (float)

Display records in format:


Item No:
Item Name:

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
59
CHAPTER2 December 2, 2025

Quantity:
Price per item:
Amount: (Price * Qty)

Answer:

import pickle

# Writing records

R
with open("[Link]", "wb") as f:
while True:

L
item_no = int(input("Enter Item No (0 to stop): "))
if item_no == 0: break

N
name = input("Item Name: ")
qty = int(input("Quantity: "))

EE
price = float(input("Price: "))
[Link]([item_no, name, qty, price], f)

# Reading records H
AT
with open("[Link]", "rb") as f:
while True:
try:
M

item = [Link](f)
print(f"\nItem No: {item[0]}")
ED

print(f"Item Name: {item[1]}")


print(f"Quantity: {item[2]}")
print(f"Price per item: {item[3]}")
M

print(f"Amount: {item[2] * item[3]}")


except EOFError:
M

break
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., [Link]., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
60

You might also like