0% found this document useful (0 votes)
1K views54 pages

Chapter 2 File Handling in Python

The document is a set of student notes focused on file handling in Python, covering topics such as types of files, opening and closing files, reading and writing to text files, and using the pickle module. It includes detailed explanations, syntax examples, and exercises for practice. The work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 International License.
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)
1K views54 pages

Chapter 2 File Handling in Python

The document is a set of student notes focused on file handling in Python, covering topics such as types of files, opening and closing files, reading and writing to text files, and using the pickle module. It includes detailed explanations, syntax examples, and exercises for practice. The work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 International License.
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
You are on page 1/ 54

M

O
H
A
M
M
ED
M
AT
H
EE
N
L
R
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Contents

LICENSE 4

CHAPTER 2: FILE HANDLING IN PYTHON 5


Introduction to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

R
Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Opening and Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

L
Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

N
File Access Modes with Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

EE
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
File Access Modes . . . . . . . . . . . . . .
H . . . . . . . . . . . . . . . . . . . . . . . 8
AT
File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
M

Writing to a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9


Syntax: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
ED

Example: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Syntax: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Example: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
M

Reading from a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10


M

Syntax: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Example: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
A

Syntax: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Example: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
H

Syntax: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
O

Example: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
M

Syntax: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Example: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Complete Example from Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
File Offset Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Syntax: tell() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Syntax: seek(offset, reference_point) . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
2
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Creating and Traversing a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


Creating File and Writing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Displaying File Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Combined Read/Write Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Pickle Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Pickling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Unpickling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Import Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

R
Syntax for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

L
Syntax for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Example for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

N
Example for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

EE
Complete Program Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

MULTIPLE CHOICE QUESTIONS (MCQ) 15

FILL IN THE BLANKS H 34


AT
2 MARKS QUESTIONS 36
M

3 MARKS QUESTIONS 39

5 MARKS QUESTIONS 42
ED

CHAPTER END EXERCISES 49


M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
3
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

LICENSE

This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.

R
“Karnataka Second PUC Computer Science Study Material / Student Notes” by L R Mohammed Matheen

L
is licensed under CC BY-NC-ND 4.0.

N
EE
H
AT
Figure 1: Licence
M

This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License.
ED

Portions of this work may include material under separate copyright. These materials are not covered by
this Creative Commons license and are used by permission or under applicable copyright exceptions.
M

This book is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-


tional License.
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
4
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

CHAPTER 2: FILE HANDLING IN PYTHON

Introduction to Files

• In Python, data stored in variables is temporary and disappears after the program ends.
• To store data permanently, we use files, which are saved on secondary storage (e.g., hard disks).
• Files allow us to store inputs, outputs, and objects for later use.
• A Python file (source code) is saved with a .py extension.

R
L
Types of Files

N
Files can be classified into two major types:

EE
Text Files

• H
Human-readable and stored using characters like letters, digits, symbols.
AT
• Examples: .txt, .py, .csv, etc.
• Stored using encoding formats like ASCII, Unicode.
M

• Each character is represented by its byte equivalent.


• End of Line (EOL) character (\n) is used to separate lines.
ED

Example:

The ASCII value of 'A' is 65 → Binary: 1000001


M

Binary Files
M
A

• Not human-readable (appear as symbols or garbage in text editors).


• Store data such as images, audio, video, compressed or executable files.
H

• Readable only with appropriate programs.


O
M

Opening and Closing a File

Opening a File

• Files are opened using the open() function which returns a file object.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
5
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Syntax:

file_object = open("filename", "mode")

File Access Modes with Examples

Read Mode - r

• Opens file for reading only.

R
• File must exist.

L
• File pointer at the beginning.

f = open("myfile.txt", "r")

N
EE
Binary Read Mode - rb

• Opens file in binary mode for reading.

f = open("myfile.txt", "rb") H
AT
Read and Write Mode - r+
M

• Opens file for reading and writing.


• File must exist.
ED

f = open("myfile.txt", "r+")
M

Write Mode - w
M

• Opens file for writing only.


A

• Overwrites file if it exists or creates a new one.


H

f = open("myfile.txt", "w")
O

Write Binary and Read Mode - wb+


M

• Opens file in binary mode for writing and reading.


• Overwrites or creates a new file.

f = open("myfile.txt", "wb+")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
6
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Append Mode - a

• Opens file for appending data.


• Creates file if it doesn’t exist.
• File pointer at the end.

f = open("myfile.txt", "a")

Append and Read Mode - a+

R
• Opens file for both appending and reading.

L
f = open("myfile.txt", "a+")

N
Example from textbook:

EE
myObject = open("myfile.txt", "a+")

File Attributes H
AT
file.closed # True if file is closed
file.mode # Access mode of file
M

file.name # Name of the file


ED

Closing a File
M

• Always close files after use to free system resources. Syntax:

file_object.close()
M
A

Opening a File Using with Clause


H

• Preferred method for file operations as it auto-closes the file. Syntax:


O

with open("myfile.txt", "r+") as myObject:


M

content = myObject.read()

Opening a File Syntax:

file_object = open("filename", "mode")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
7
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

File Access Modes

Mode Description File Pointer Position

r Read only Beginning


rb Read binary Beginning
r+ Read and write Beginning

R
w Write only (overwrites if exists) Beginning

L
wb+ Write and read binary (overwrites) Beginning
a Append (creates file if it doesn’t exist) End

N
a+ Append and read End

EE
Example:
H
AT
myObject = open("myfile.txt", "a+")
M

File Attributes

file.closed # True if file is closed


ED

file.mode # Access mode of file


file.name # Name of the file
M

Closing a File
M

Syntax:
A

file_object.close()
H
O

Opening a File Using with Clause


M

Syntax:

with open("myfile.txt", "r+") as myObject:


content = myObject.read()

• Automatically closes the file when the block is exited.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
8
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Writing to a Text File

Syntax: write()

file_object.write(string)

• Writes a single string to the file.


• Returns the number of characters written.

R
Example: write()

L
• Writes a single string to the file.

N
myobject = open("myfile.txt", 'w')

EE
myobject.write("Hey I have started using files in Python\n")
myobject.close()

Writing numbers:
H
AT
marks = 58
myobject.write(str(marks))
M

Syntax: writelines()
ED

file_object.writelines(list_of_strings)
M

• Writes multiple strings to the file.


• Takes an iterable like a list or tuple.
M

Example: writelines()
A
H

• Writes a sequence (like a list or tuple) of strings.


O

lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
myobject.writelines(lines)
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
9
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Reading from a Text File

Syntax: read(n)

file_object.read(n)

• Reads n bytes from the file.

R
Example: read(n)

L
• Reads n bytes from the file.

myobject = open("myfile.txt", 'r')

N
print(myobject.read(10))

EE
myobject.close()

Syntax: read()
H
AT
file_object.read()

• Reads the entire content of the file.


M

Example: read()
ED

• Reads the entire file content.

myobject = open("myfile.txt", 'r')


M

print(myobject.read())
M

myobject.close()
A

Syntax: readline(n)
H

file_object.readline(n)
O

• Reads one line or up to n bytes until newline character.


M

Example: readline(n)

• Reads one line or n bytes until newline.

myobject = open("myfile.txt", 'r')


print(myobject.readline(10))
myobject.close()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
10
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Syntax: readlines()

file_object.readlines()

• Reads all lines and returns them as a list.

Example: readlines()

R
• Reads all lines and returns a list.

myobject = open("myfile.txt", 'r')

L
print(myobject.readlines())

N
myobject.close()

EE
Splitting into words:

for line in lines:


words = line.split()
print(words) H
AT
Using splitlines():
M

for line in lines:


print(line.splitlines())
ED

Complete Example from Text


M

fobject = open("testfile.txt", "w")


sentence = input("Enter the contents to be written in the file: ")
M

fobject.write(sentence)
fobject.close()
A

print("Now reading the contents of the file: ")


H

fobject = open("testfile.txt", "r")


O

for str in fobject:


print(str)
M

fobject.close()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
11
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

File Offset Methods

Syntax: tell()

file_object.tell()

• Returns current position of file pointer.

• Returns current file pointer position.

R
file_object.tell()

L
Syntax: seek(offset, reference_point)

N
file_object.seek(offset, reference_point)

EE
• Moves pointer to specified position from reference point (0 = start, 1 = current, 2 = end).

• Moves pointer to specified position.


H
AT
file_object.seek(5, 0) # Move to 5th byte from start

Program Example:
M

fileobject = open("testfile.txt", "r+")


str = fileobject.read()
ED

print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
M

print("Now at beginning:", fileobject.tell())


fileobject.seek(10)
M

print("Pointer at:", fileobject.tell())


print(fileobject.read())
A

fileobject.close()
H
O
M

Creating and Traversing a Text File

Creating File and Writing Data

fileobject = open("practice.txt", "w+")


while True:
data = input("Enter data to save in the text file: ")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
12
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

fileobject.write(data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n': break
fileobject.close()

Displaying File Contents

fileobject = open("practice.txt", "r")

R
str = fileobject.readline()
while str:

L
print(str)
str = fileobject.readline()

N
fileobject.close()

EE
Combined Read/Write Program

fileobject = open("report.txt", "w+")


H
AT
while True:
line = input("Enter a sentence ")
fileobject.write(line + "\n")
M

choice = input("Do you wish to enter more data? (y/n): ")


if choice.lower() == 'n': break
ED

print("File position:", fileobject.tell())


fileobject.seek(0)
print("Reading contents:")
M

print(fileobject.read())
fileobject.close()
M
A
H

Pickle Module
O

Pickling
M

• Process of converting Python objects to a byte stream (serialization).


• Can store complex objects like lists, dictionaries.

Unpickling

• Restores the byte stream back into original object (deserialization).

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
13
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Import Statement

import pickle

Syntax for dump()

pickle.dump(object, file_object)

R
Syntax for load()

L
variable = pickle.load(file_object)

N
EE
Example for dump()

listvalues = [1, "Geetika", 'F', 26]


fileobject = open("mybinary.dat", "wb")
pickle.dump(listvalues, fileobject) H
AT
fileobject.close()
M

Example for load()


ED

fileobject = open("mybinary.dat", "rb")


objectvar = pickle.load(fileobject)
fileobject.close()
M

print(objectvar)
M

Complete Program Example


A

import pickle
H

bfile = open("empfile.dat", "ab")


recno = 1
O

while True:
M

eno = int(input("Employee number: "))


ename = input("Name: ")
ebasic = int(input("Basic Salary: "))
allow = int(input("Allowances: "))
totsal = ebasic + allow
edata = [eno, ename, ebasic, allow, totsal]
pickle.dump(edata, bfile)
if input("More records? (y/n): ").lower() == 'n': break

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
14
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

print("File size:", bfile.tell())


bfile.close()

print("Reading employee records")


try:
with open("empfile.dat", "rb") as bfile:
while True:
edata = pickle.load(bfile)
print(edata)

R
except EOFError:
pass

L
N
MULTIPLE CHOICE QUESTIONS (MCQ)

EE
1. Introduction to Files

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


H
AT
a) To execute programs faster
M

b) To permanently store data for later access


ED

c) To reduce memory usage

d) To improve program readability


M

Answer: b) To permanently store data for later access


M

2. Where are files stored in a computer system?


A

a) Primary memory (RAM)


H

b) Secondary storage media


O

c) CPU registers
M

d) Cache memory
Answer: b) Secondary storage media

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
15
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

a) .txt

b) .jpg

c) .exe

R
d) .mp3

L
Answer: a) .txt

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

EE
a) Text files are smaller in size

b) Binary files contain human-readable characters


H
AT
c) Text files consist of ASCII/Unicode characters
M

d) Binary files cannot be opened in Python


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

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

a) It displays the correct content


M

b) It shows garbage values


M
A

c) It automatically converts to text


H

d) It asks for a password


O

Answer: b) It shows garbage values


M

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

a) A .csv file

b) A .py file

c) A .docx file

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
16
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

d) A .txt file
Answer: c) A .docx file

7. What is the default EOL character in Python?

a) \r

b) \n

R
c) \t

L
d) \0

N
Answer: b) \n

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

a) ASCII

H
AT
b) JPEG

c) MPEG
M

d) ZIP
ED

Answer: a) ASCII
M
M

3. Opening and Closing Files


A

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


H

a) file_open()
O

b) open()
M

c) load()

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

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
17
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

a) Read mode (‘r’)

b) Write mode (‘w’)

c) Append mode (‘a’)

d) Binary mode (‘b’)


Answer: a) Read mode (‘r’)

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

L
a) ‘r’

N
b) ‘w+’

EE
c) ‘a’

H
AT
d) ‘b’
Answer: b) ‘w+’
M

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

a) The file is opened in read mode


ED

b) The existing content is overwritten


M

c) The file is deleted


M

d) An error occurs
A

Answer: b) The existing content is overwritten


H

13. Which attribute returns the access mode of a file?


O

a) file.name
M

b) file.mode

c) file.closed

d) file.size
Answer: b) file.mode

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
18
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

14. How is a file closed in Python?

a) file.close()

b) close(file)

c) file.exit()

R
d) exit(file)
Answer: a) file.close()

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

N
a) It allows faster file operations

EE
b) It automatically closes the file

c) It encrypts the file H


AT
d) It compresses the file
M

Answer: b) It automatically closes the file


ED

4. Writing to a Text File


M

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


M

a) writeline()
A

b) write()
H
O

c) append()
M

d) insert()
Answer: b) write()

17. What does the write() method return?

a) The number of characters written

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
19
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

b) The file object

c) The content of the file

d) None
Answer: a) The number of characters written

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

R
a) Directly using write()

L
b) By converting it to a string first

N
c) Using the dump() method

EE
d) It cannot be written
Answer: b) By converting it to a string first
H
AT
19. Which method is used to write multiple strings to a file?

a) writelines()
M

b) write()
ED

c) appendlines()
M

d) insertlines()
M

Answer: a) writelines()

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


A
H

a) To close the file


O

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


M

c) To read the file

d) To delete the file


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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
20
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

5. Reading from a Text File


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

a) read()

b) readline()

c) readlines()

R
d) seek()

L
Answer: a) read()

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

EE
a) It reads one line

b) It reads the entire file


H
AT
c) It returns an error
M

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

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

a) read()
M

b) readline()
M
A

c) readlines()
H

d) load()
O

Answer: b) readline()
M

24. What does the readlines() method return?

a) A single string

b) A list of strings

c) A tuple of strings

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
21
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

d) A dictionary of strings
Answer: b) A list of strings

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

a) Using readline() in a while loop

b) Using read() in a for loop

R
c) Using seek() in a loop

L
d) Using dump() in a loop

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

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

a) Splits the file into multiple files

H
AT
b) Splits each line into a list of words

c) Joins multiple lines


M

d) Closes the file


ED

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


M
M

6. Setting Offsets in a File


A

27. Which method returns the current position of the file object?
H

a) seek()
O

b) tell()
M

c) pos()

d) offset()
Answer: b) tell()

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
22
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

a) To close the file

b) To move the file object to a specific position

c) To read the file

d) To write to the file


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

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

L
a) Beginning of the file (0)

N
b) Current position (1)

EE
c) End of the file (2)

H
AT
d) Middle of the file
Answer: a) Beginning of the file (0)
M

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

a) seek(10, 0)
ED

b) seek(0, 10)
M

c) seek(10, 1)
M

d) seek(10, 2)
A

Answer: a) seek(10, 0)
H
O
M

7. Creating and Traversing a Text File

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

a) An error occurs

b) A new file is created

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
23
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

c) The file is deleted

d) The file is opened in read mode


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+’

R
b) ‘w+’

L
c) ‘a+’

N
d) ‘b+’

EE
Answer: c) ‘a+’

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


H
AT
a) Using a for loop on the file object

b) Using a while loop with readline()


M

c) Both a and b
ED

d) Using seek()
Answer: c) Both a and b
M

34. What is the output of fileobject.tell() after writing data to a file?


M

a) The number of lines written


A
H

b) The current byte position of the file object


O

c) The file size


M

d) The number of characters written


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

8. The Pickle Module

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
24
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

35. What is the purpose of the pickle module?

a) To read text files

b) To serialize and deserialize Python objects

c) To write binary files

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

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

N
a) write()

EE
b) dump()

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

Answer: b) dump()

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

a) read()
M

b) load()
M

c) get()
A

d) unpickle()
H

Answer: b) load()
O

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


M

a) ‘w’

b) ‘wb’

c) ‘wr’

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
25
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

39. What happens if a binary file is corrupted?

a) It can be easily fixed

b) It becomes unreadable

R
c) It automatically repairs itself

L
d) It converts to a text file

N
Answer: b) It becomes unreadable

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

a) FileNotFoundError

H
AT
b) EOFError

c) IOError
M

d) ValueError
ED

Answer: b) EOFError
M
M

Miscellaneous
A

41. What is serialization?


H

a) Converting Python objects to byte streams


O

b) Reading text files


M

c) Writing binary files

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

42. What is deserialization?

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
26
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

a) Converting byte streams to Python objects

b) Writing text files

c) Reading binary files

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

R
43. Which module is required for pickling and unpickling?

L
a) io

N
b) pickle

EE
c) os

H
AT
d) sys
Answer: b) pickle
M

44. What is the output of file.closed if the file is open?

a) True
ED

b) False
M

c) 1
M

d) 0
A

Answer: b) False
H

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


O

a) close()
M

b) flush()

c) write()

d) dump()
Answer: b) flush()

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
27
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

a) To split a file into multiple files

b) To split a string into a list of lines

c) To join lines in a file

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

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

N
a) file.name

EE
b) file.mode

c) file.size H
AT
d) file.closed
M

Answer: c) file.size

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

a) open(“file.dat”, “r+b”)
M

b) open(“file.dat”, “rwb”)
M

c) open(“file.dat”, “br+”)
A

d) open(“file.dat”, “b+r”)
H

Answer: a) open(“file.dat”, “r+b”)


O

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


M

a) with open(“file.txt”, “r”) as f:

b) with open(“file.txt”, “r”) -> f:

c) with open(“file.txt”, “r”) in f:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
28
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

d) with open(“file.txt”, “r”) f:


Answer: a) with open(“file.txt”, “r”) as f:

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

a) To handle file operations

b) To perform mathematical calculations

R
c) To create graphical interfaces

L
d) To connect to databases

N
Answer: a) To handle file operations

EE
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:
H
AT
(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
M

(D) A is false, but R is true

Answer: A
ED
M

52. Assertion (A): Binary files can be edited easily using Notepad or any text editor.
M

Reason (R): Binary files store information using human-readable characters.


A

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

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

(C) A is true, but R is false


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

Answer: D

53. Assertion (A): The open() function returns a file object.


Reason (R): This file object is used to perform read or write operations.

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
29
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

(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: A

54. Assertion (A): Files should be closed using the close() method after operations.
Reason (R): Closing a file ensures that all data is flushed and memory is freed.

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
(C) A is true, but R is false

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

EE
Answer: A

H
55. Assertion (A): The write() method automatically adds a newline character at the end of the
string.
AT
Reason (R): It is designed to make each write call write a new line.

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
ED

(C) A is true, but R is false


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

Answer: D
M
A

56. Assertion (A): The writelines() method requires a list or tuple of strings.
H

Reason (R): It adds newline characters between each string automatically.


O

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
(C) A is true, but R is false
(D) A is false, but R is true

Answer: C

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
30
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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.

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

R
Answer: C

L
N
58. Assertion (A): The read() method reads the complete file when no parameter is passed.

EE
Reason (R): It returns a list of strings when the file is completely read.

Options:

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

(D) A is false, but R is true

Answer: C
ED

59. Assertion (A): The readline() method reads the file until a newline character is found.
Reason (R): It always reads the complete file in one go.
M

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

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

(C) A is true, but R is false


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

Answer: C
O
M

60. Assertion (A): The readlines() method returns a list containing each line as an element.
Reason (R): This method is useful when we want to iterate through lines as list elements.

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
31
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

(C) A is true, but R is false


(D) A is false, but R is true

Answer: A

61. Assertion (A): The tell() function returns the current byte position of the file object.
Reason (R): It is helpful when tracking file offset during file operations.

Options:

R
(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

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

N
Answer: A

EE
H
62. Assertion (A): The seek() method is used to randomly access a file.
AT
Reason (R): It always moves the file pointer to the beginning of the file.
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: C
M

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

Options:
H

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


O

(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

64. Assertion (A): Pickling converts a Python object into a byte stream.
Reason (R): It is useful for storing Python objects in binary files.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
32
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 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: A

65. Assertion (A): The dump() method writes binary data to a file.

R
Reason (R): The file must be opened in 'rb' mode to use dump().

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

N
(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

Answer: C
H
AT
(dump() requires 'wb', not 'rb')

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

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

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

Answer: A
A

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


H

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

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

(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: D
(Not all objects can be pickled – open files, sockets, etc., cannot be.)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
33
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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
(D) A is false, but R is true

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

L
N
EE
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.

Options:
H
AT
(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
ED

Answer: C

70. Assertion (A): pickle.load() 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.
M

Options:
(A) Both A and R are true, and R is the correct explanation of A
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
H

(D) A is false, but R is true


O

Answer: A
M

FILL IN THE BLANKS

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
34
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

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+’

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

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

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

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

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

H
14. To read a specified number of bytes from a file, we use the ________ method. Answer: read()
AT
15. The ________ method reads one complete line from a file. Answer: readline()

16. The ________ method reads all lines and returns them as a list. Answer: readlines()
M

17. The ________ module is used for serializing and deserializing Python objects. Answer: pickle
ED

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

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

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

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

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

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

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

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

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

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

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., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
35
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 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
2. What is the purpose of file modes? Give syntax to open a file in read-write mode.

N
Answer:

EE
File modes determine operations allowed on a file.
Syntax: file_object = open("filename.txt", "r+")

H
3. Explain the difference between write() and writelines() methods with examples.
Answer:
AT
• write(): Writes a single string (file.write("Hello"))
M

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


ED

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

• ‘w’ mode overwrites existing content.


M

• ‘a’ mode appends to existing content.


A

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


Answer:
H

• tell(): Returns current position (pos = file.tell())


O
M

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


5th byte from start).

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


Answer:

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
36
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

• readline(): Reads one line.

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

7. Why is closing files important? Show two ways to close a file.


Answer:
Prevents memory leaks and ensures data is saved.
Methods:

R
1. Explicit: file.close()

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

N
8. What is pickling? Give syntax to dump a Python list into a binary file.

EE
Answer:
Pickling converts Python objects to byte streams.
Syntax:
H
AT
import pickle
pickle.dump([1, 2, 3], open("data.dat", "wb"))
M

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

Splits strings into lists.


Example:
M

line = "Hello World"


words = line.split() # Returns ['Hello', 'World']
M

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


A

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

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


O

Answer:
M

• ‘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.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
37
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

data = pickle.load(open("file.dat", "rb"))

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

• ‘r’ mode raises FileNotFoundError.

R
• ‘w’ mode creates a new file.

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

N
Answer:

EE
File offsets indicate byte positions.
Example: file.seek(10) moves pointer to 10th byte.

H
16. How does append mode (‘a’) differ from write mode (‘w’) in file handling?
Answer:
AT
• ‘a’ preserves existing content and adds new data at the end.
M

• ‘w’ deletes existing content.


ED

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


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

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


M

Answer:
A

with open("file.txt", "r") as f:


for line in f:
H

print(line)
O

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

Answer:

• file.name: Returns filename.

• file.mode: Returns access mode.

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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
38
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

• dump(): Writes objects to binary files.

• load(): Reads objects from binary files.

3 MARKS QUESTIONS

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

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

L
• Perform operations (read/write) using appropriate methods
• Close file using close() method to free resources

N
• Alternatively use with statement for automatic closing

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

• Store human-readable characters


• Use ASCII/Unicode encoding H
AT
• Extensions: .txt, .py, .csv

Binary Files:
M

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


ED

• Non-human readable format


• Extensions: .dat, .jpg, .mp3
M

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

• 'r': Read mode (default) - open("file.txt", "r")


M

• 'w': Write mode (overwrites) - open("file.txt", "w")


A

• 'a': Append mode - open("file.txt", "a")


H

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

with open("sample.txt", "w") as f:


f.write("First line\n")
M

f.write("Second line\n")
f.write("Third line\n")

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

• tell(): Returns current position


pos = file.tell() # Returns byte position

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
39
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

• seek(): Moves file pointer


file.seek(5) # Moves to 5th byte
file.seek(0, 2) # Moves to end of file

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

• read(): Reads entire content or specified bytes


• readline(): Reads single line

R
• readlines(): Returns list of all lines

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

L
• Used for object serialization

N
• dump(): Writes object to file

EE
pickle.dump(obj, file)

• load(): Reads object from file


H
AT
obj = pickle.load(file)

8. Write a program to read a file and display lines starting with ‘A’.
M

with open("data.txt", "r") as f:


for line in f:
ED

if line.startswith('A'):
print(line)
M

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

• Automatically closes file


M

• Handles exceptions properly


A

• Cleaner and more readable code


H

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

• write(): Accepts single string


M

file.write("Hello")

• writelines(): Accepts sequence of strings


file.writelines(["Line1", "Line2"])

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

• Serialization: Converting object to byte stream (pickling)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
40
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

• Deserialization: Converting byte stream back to object (unpickling)


• Done using pickle module

12. Write a program to copy contents from one file to another.

with open("source.txt", "r") as src, open("dest.txt", "w") as dest:


dest.write(src.read())

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

R
• file.name: Returns filename

L
print(file.name)

• file.mode: Returns access mode

N
print(file.mode)

EE
• file.closed: Returns True if closed
print(file.closed)
H
AT
14. What are the different reference points in seek() method? Explain. Answer:

• 0: Beginning of file (default)


M

• 1: Current position
• 2: End of file Example: file.seek(5, 0) moves to 5th byte from start
ED

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

count = 0
M

with open("data.txt", "r") as f:


for line in f:
M

count += 1
print("Total lines:", count)
A

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


H

• Frees system resources


O

• Ensures all data is written


M

• Prevents data corruption


• Releases file locks

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

• 'r+': Read/write (file must exist)


• 'w+': Read/write (creates/overwrites)
• 'a+': Read/append (creates if doesn’t exist)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
41
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

18. Write a program to display the size of a file.

import os
size = os.path.getsize("data.txt")
print("File size:", size, "bytes")

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

• split(): Splits at whitespace

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

L
• splitlines(): Splits at line breaks
lines = "Line1\nLine2".splitlines() # ['Line1', 'Line2']

N
20. Write a program to create a binary file and store a dictionary in it.

EE
import pickle
data = {"name": "John", "age": 25}
with open("data.dat", "wb") as f:
H
AT
pickle.dump(data, f)
M

5 MARKS QUESTIONS
ED

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

• Opening: file = open("example.txt", "r") or with open("example.txt", "w")


as file:
M

• Writing: file.write("Content") or file.writelines(["Line1\n", "Line2\n"])


• Reading: content = file.read() or lines = file.readlines()
A

• Positioning: pos = file.tell() and file.seek(offset)


H

• Closing: file.close() (automatic in with statement) Example:


O

with open("demo.txt", "w+") as f:


f.write("Sample text\n")
M

f.seek(0)
print(f.read())

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

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


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

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
42
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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


• Use Cases: Text for configuration/data; Binary for media/executables
• Example:
# Text file operation
with open("text.txt", "w") as f:
f.write("Hello")

# Binary file operation

R
with open("binary.dat", "wb") as f:
f.write(b'\x48\x65\x6c\x6c\x6f')

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

N
use cases. Answer:

EE
Mode Pointer Position Use Case

‘r’ Beginning Read existing files


H
AT
‘w’ Beginning Create/overwrite files
‘a’ End Append to existing files
M

‘r+’ Beginning Read/write existing files


‘w+’ Beginning Create/overwrite with read capability
ED

‘a+’ End Append with read capability


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

4. Demonstrate the complete process of pickling and unpickling with proper error handling.
Answer:
A

import pickle
H
O

# Pickling (Serialization)
try:
M

data = {"name": "Alice", "age": 25}


with open("data.dat", "wb") as f:
pickle.dump(data, f)
except pickle.PicklingError:
print("Error in pickling data")

# Unpickling (Deserialization)
try:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
43
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

with open("data.dat", "rb") as f:


loaded = pickle.load(f)
print(loaded)
except (pickle.UnpicklingError, EOFError):
print("Error in unpickling data")

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

• Attributes:

R
– name: print(file.name) # Shows filename
– mode: print(file.mode) # Shows access mode

L
– closed: print(file.closed) # True/False

N
• Methods:

EE
– read(): content = file.read(10) # First 10 bytes
– seek(): file.seek(5) # Move to 5th byte
– tell(): pos = file.tell() # Current position
– flush(): file.flush() # Force write to disk
H
AT
6. Develop a complete Python program to maintain student records in a file with the following
operations: add, view, and search records. Answer:
M

def add_student():
with open("students.txt", "a") as f:
ED

name = input("Enter name: ")


roll = input("Enter roll no: ")
f.write(f"{roll},{name}\n")
M

def view_students():
M

with open("students.txt", "r") as f:


print("\nStudent Records:")
A

for line in f:
H

roll, name = line.strip().split(',')


print(f"Roll: {roll}, Name: {name}")
O
M

def search_student():
roll = input("Enter roll no to search: ")
with open("students.txt", "r") as f:
for line in f:
if line.startswith(roll):
print("Record found:", line)
return
print("Record not found")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
44
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

• Sequential Access:
– Reads/writes in order
– Methods: read(), readline(), write()
– Example:
with open("seq.txt", "r") as f:

R
while True:
line = f.readline()

L
if not line: break
print(line)

N
• Random Access:

EE
– Direct access using positions
– Methods: seek(), tell()
– Example:
H
AT
with open("random.txt", "rb+") as f:
f.seek(10)
f.write(b"NEWDATA")
M

print("Current position:", f.tell())

8. Explain the concept of serialization with its advantages and demonstrate using the pickle
ED

module. Answer:

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


M

• Advantages:
M

1. Preserves object state


A

2. Enables complex data storage


3. Supports network transmission
H

• Example:
O

import pickle
M

# Serialization
data = {"a": [1,2,3], "b": ("hello",), "c": {"key": "value"}}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)

# Deserialization
with open("data.pkl", "rb") as f:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
45
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

loaded = pickle.load(f)
print(loaded)

9. Develop a complete file handling program that demonstrates reading, writing, and appending
operations with proper exception handling. Answer:

try:
# Writing
with open("operations.txt", "w") as f:

R
f.write("Initial content\n")

L
# Appending
with open("operations.txt", "a") as f:

N
f.write("Appended content\n")

EE
# Reading
with open("operations.txt", "r") as f:
print("File content:")
print(f.read()) H
AT
except IOError as e:
print(f"File error: {e}")
M

except Exception as e:
print(f"Error: {e}")
ED

10. Explain the various techniques for reading file content in Python with examples of when each
would be appropriate. Answer:
M

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


M

with open("data.txt", "r") as f:


content = f.read() # For small files
A

• readline(): When processing large files line by line


H

with open("large.txt", "r") as f:


O

while True:
line = f.readline()
M

if not line: break


process(line)

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


with open("config.txt", "r") as f:
lines = f.readlines() # For line-based operations

• Iteration: Memory efficient for large files

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
46
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

with open("huge.txt", "r") as f:


for line in f: # No memory overload
process(line)

11. Create a comprehensive program that demonstrates all file object methods (read, write,
seek, tell, flush) with proper documentation.
Answer:

R
# Demonstrate all key file methods
with open("demo_methods.txt", "w+") as f: # Open in write/read mode

L
# WRITE
f.write("Line 1\nLine 2\nLine 3\n")

N
print(f"Initial write - Position: {f.tell()}") # Should show 18 bytes

EE
# FLUSH
f.flush() # Force write to disk

# SEEK H
AT
f.seek(0) # Rewind to start
print(f"After seek(0) - Position: {f.tell()}") # 0
M

# READ
content = f.read(10) # First 10 chars
ED

print(f"Partial read: {content}")


print(f"After read(10) - Position: {f.tell()}") # 10
M

# READLINE
f.seek(0)
M

print("Full content:")
while True:
A

line = f.readline()
H

if not line: break


print(line.strip())
O

12. Compare and contrast the working of text mode vs binary mode file operations with suitable
M

examples for each.


Answer:

Aspect Text Mode Binary Mode

Data Handling Automatic encoding/decoding Raw bytes

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
47
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

Aspect Text Mode Binary Mode

Newlines Converts \n to OS format No conversion


Example Write f.write("Hello") f.write(b"Hello")
Example Read text = f.read() data = f.read()
Use Case Config files, logs Images, serialized data

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

L
practical applications.
Answer:

N
EE
• Reference Points:

1. 0 (default): Beginning of file


H
AT
2. 1: Current position
M

3. 2: End of file
ED

• Applications:

# Jump to beginning
M

f.seek(0)
M

# Move 5 bytes forward from current position


f.seek(5, 1)
A
H

# Go to 10 bytes before end


f.seek(-10, 2)
O

# Practical use: Read last line


M

f.seek(-100, 2) # Move near end


last_line = f.readlines()[-1]

14. Develop a program that demonstrates reading a binary file (like an image) and creating its
copy.
Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
48
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

def copy_binary_file(source, dest):


CHUNK_SIZE = 4096 # 4KB chunks
with open(source, "rb") as src, open(dest, "wb") as dst:
while True:
chunk = src.read(CHUNK_SIZE)
if not chunk: break
dst.write(chunk)

# Usage

R
copy_binary_file("original.jpg", "copy.jpg")

L
CHAPTER END EXERCISES

N
EE
1. Differentiate between:

a) Text file and binary file


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

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

.jpg.

b) readline() and readlines()


M

Answer:
M

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


A

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


H
O

c) write() and writelines()


Answer:
M

• write() accepts a single string argument.

• writelines() accepts an iterable of strings.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
49
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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

a) open()
Answer:

• Use: To open a file

• Syntax: file_object = open(filename, mode)

R
b) read()

L
Answer:

N
EE
• Use: Reads file content

• Syntax: content = file_object.read([size])

c) seek() H
AT
Answer:
M

• Use: Moves file pointer


ED

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

d) dump()
M

Answer:
M

• Use: Writes Python objects to binary files


A
H

• Syntax: pickle.dump(object, file_object)


O
M

3. Write the file mode that will be used for opening the following files. Also, write the
Python statements to open the following files:

a) A text file “example.txt” in both read and write mode


Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
50
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

• Mode: 'r+'

• Statement: file = open("example.txt", "r+")

b) A binary file “bfile.dat” in write mode


Answer:

• Mode: 'wb'

R
L
• Statement: file = open("bfile.dat", "wb")

N
c) A text file “try.txt” in append and read mode
Answer:

EE
• Mode: 'a+'

H
AT
• Statement: file = open("try.txt", "a+")

d) A binary file “btry.dat” in read only mode


M

Answer:
ED

• Mode: 'rb'
M

• Statement: file = open("btry.dat", "rb")


M
A

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

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

- Prevents memory leaks and data corruption.


- Unclosed files may remain locked, preventing other operations.
M

- No immediate error, but may cause resource issues.

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

a)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
51
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

P = open("practice.txt","r")
P.read(10)

b)

with open("practice.txt","r") as P:
x = P.read()

Answer:

R
- (a) Requires manual closing (P.close()).
- (b) Automatically closes file after block.

L
N
EE
6. Write a command(s) to write the following lines to the text file named hello.txt. Assume
that the file is opened in append mode. “Welcome my class”
“It is a fun place”
H
AT
“You will learn and play”
Answer:
M

with open("hello.txt", "a") as f:


f.write("Welcome my class\n")
f.write("It is a fun place\n")
ED

f.write("You will learn and play\n")


M
M

7. Write a Python program to open the file hello.txt 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
A

instead of append mode? Answer:


H

# Read mode
O

with open("hello.txt", "r") as f:


print(f.read())
M

# Write mode would overwrite all content

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
52
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

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
uppercase alphabet. Answer:

with open("output.txt", "w") as f:


while True:
line = input("Enter sentence (END to stop): ")
if line == "END": break
f.write(line + "\n")

R
# Display filtered content

L
with open("output.txt", "r") as f:
for line in f:

N
if line.strip() and line[0].isupper():

EE
print(line.strip())

H
AT
9. Define pickling in Python. Explain serialization and deserialization of Python object.
Answer:
M

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


- Serialization: Object → Byte stream (using pickle.dump()).
ED

- Deserialization: Byte stream → Object (using pickle.load()).


M
M

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

Qty (integer)
H

Price (float)
O

Display records in format:


Item No:
M

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

Answer:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
53
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON April 16, 2025

import pickle

# Writing records
with open("items.dat", "wb") as f:
while True:
item_no = int(input("Enter Item No (0 to stop): "))
if item_no == 0: break
name = input("Item Name: ")
qty = int(input("Quantity: "))

R
price = float(input("Price: "))
pickle.dump([item_no, name, qty, price], f)

L
N
# Reading records
with open("items.dat", "rb") as f:

EE
while True:
try:
item = pickle.load(f)
print(f"\nItem No: {item[0]}")
H
AT
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:
break
ED

For more information Visit:


M

https://matheenhere.blogspot.com
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


LECTURER, PRIMUS PU COLLEGE, BANGALORE - 560 035
54

You might also like