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

Chap 2 File Handling in Python

Chapter 2 of the document covers file handling in Python, explaining the importance of files for permanent data storage and classifying them into text and binary types. It details how to open and close files using the open() function, along with various file access modes and their examples. The chapter also includes practical examples and exercises related to file operations.

Uploaded by

prajuteju2008
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 views53 pages

Chap 2 File Handling in Python

Chapter 2 of the document covers file handling in Python, explaining the importance of files for permanent data storage and classifying them into text and binary types. It details how to open and close files using the open() function, along with various file access modes and their examples. The chapter also includes practical examples and exercises related to file operations.

Uploaded by

prajuteju2008
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/ 53

STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Contents

LICENSE 4

CHAPTER 2: FILE HANDLING IN PYTHON 5


Introduction to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Opening and Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
File Access Modes with Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
File Access Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Opening a File Using with Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Writing to a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Syntax: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Example: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Syntax: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Example: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Reading from a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Syntax: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Example: read(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Syntax: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Example: read() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Syntax: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Example: readline(n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Syntax: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Example: readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Complete Example from Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
File Offset Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Syntax: tell() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Syntax: seek(offset, reference_point) . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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
Syntax for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Syntax for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Example for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Example for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Complete Program Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

MULTIPLE CHOICE QUESTIONS (MCQ) 15

FILL IN THE BLANKS 34

2 MARKS QUESTIONS 36

3 MARKS QUESTIONS 39

5 MARKS QUESTIONS 42

CHAPTER END EXERCISES 49

3
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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.

Types of Files

Files can be classified into two major types:

Text Files

• Human-readable and stored using characters like letters, digits, symbols.


• Examples: .txt, .py, .csv, etc.
• Stored using encoding formats like ASCII, Unicode.
• Each character is represented by its byte equivalent.
• End of Line (EOL) character (\n) is used to separate lines.

Example:

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

Binary Files

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


• Store data such as images, audio, video, compressed or executable files.
• Readable only with appropriate programs.

Opening and Closing a File

Opening a File

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

5
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Syntax:

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

File Access Modes with Examples

Read Mode - r

• Opens file for reading only.


• File must exist.
• File pointer at the beginning.

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

Binary Read Mode - rb

• Opens file in binary mode for reading.

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

Read and Write Mode - r+

• Opens file for reading and writing.


• File must exist.

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

Write Mode - w

• Opens file for writing only.


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

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

Write Binary and Read Mode - wb+

• Opens file in binary mode for writing and reading.


• Overwrites or creates a new file.

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

6
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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+

• Opens file for both appending and reading.

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

Example from textbook:

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

File Attributes

file.closed # True if file is closed


file.mode # Access mode of file
file.name # Name of the file

Closing a File

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

file_object.close()

Opening a File Using with Clause

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

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


content = myObject.read()

Opening a File Syntax:

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

7
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

File Access Modes

Mode Description File Pointer Position

r Read only Beginning


rb Read binary Beginning
r+ Read and write Beginning
w Write only (overwrites if exists) Beginning
wb+ Write and read binary (overwrites) Beginning
a Append (creates file if it doesn’t exist) End
a+ Append and read End

Example:

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

File Attributes

file.closed # True if file is closed


file.mode # Access mode of file
file.name # Name of the file

Closing a File

Syntax:

file_object.close()

Opening a File Using with Clause

Syntax:

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


content = myObject.read()

• Automatically closes the file when the block is exited.

8
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Writing to a Text File

Syntax: write()

file_object.write(string)

• Writes a single string to the file.


• Returns the number of characters written.

Example: write()

• Writes a single string to the file.

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


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

Writing numbers:

marks = 58
myobject.write(str(marks))

Syntax: writelines()

file_object.writelines(list_of_strings)

• Writes multiple strings to the file.


• Takes an iterable like a list or tuple.

Example: writelines()

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

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

9
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Reading from a Text File

Syntax: read(n)

file_object.read(n)

• Reads n bytes from the file.

Example: read(n)

• Reads n bytes from the file.

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


print(myobject.read(10))
myobject.close()

Syntax: read()

file_object.read()

• Reads the entire content of the file.

Example: read()

• Reads the entire file content.

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


print(myobject.read())
myobject.close()

Syntax: readline(n)

file_object.readline(n)

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

Example: readline(n)

• Reads one line or n bytes until newline.

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


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

10
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Syntax: readlines()

file_object.readlines()

• Reads all lines and returns them as a list.

Example: readlines()

• Reads all lines and returns a list.

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


print(myobject.readlines())
myobject.close()

Splitting into words:

for line in lines:


words = line.split()
print(words)

Using splitlines():

for line in lines:


print(line.splitlines())

Complete Example from Text

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


sentence = input("Enter the contents to be written in the file: ")
fobject.write(sentence)
fobject.close()

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


fobject = open("testfile.txt", "r")
for str in fobject:
print(str)
fobject.close()

11
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

File Offset Methods

Syntax: tell()

file_object.tell()

• Returns current position of file pointer.

• Returns current file pointer position.

file_object.tell()

Syntax: seek(offset, reference_point)

file_object.seek(offset, reference_point)

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

• Moves pointer to specified position.

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

Program Example:

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


str = fileobject.read()
print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
print("Now at beginning:", fileobject.tell())
fileobject.seek(10)
print("Pointer at:", fileobject.tell())
print(fileobject.read())
fileobject.close()

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

12
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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


str = fileobject.readline()
while str:
print(str)
str = fileobject.readline()
fileobject.close()

Combined Read/Write Program

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


while True:
line = input("Enter a sentence ")
fileobject.write(line + "\n")
choice = input("Do you wish to enter more data? (y/n): ")
if choice.lower() == 'n': break

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


fileobject.seek(0)
print("Reading contents:")
print(fileobject.read())
fileobject.close()

Pickle Module

Pickling

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

13
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

Import Statement

import pickle

Syntax for dump()

pickle.dump(object, file_object)

Syntax for load()

variable = pickle.load(file_object)

Example for dump()

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


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

Example for load()

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


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

Complete Program Example

import pickle
bfile = open("empfile.dat", "ab")
recno = 1
while True:
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

14
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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)
except EOFError:
pass

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

c) To reduce memory usage

d) To improve program readability


Answer: b) To permanently store data for later access

2. Where are files stored in a computer system?

a) Primary memory (RAM)

b) Secondary storage media

c) CPU registers

d) Cache memory
Answer: b) Secondary storage media

15
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

a) .txt

b) .jpg

c) .exe

d) .mp3
Answer: a) .txt

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

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

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

a) It displays the correct content

b) It shows garbage values

c) It automatically converts to text

d) It asks for a password


Answer: b) It shows garbage values

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

a) A .csv file

b) A .py file

c) A .docx file

16
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

7. What is the default EOL character in Python?

a) \r

b) \n

c) \t

d) \0
Answer: b) \n

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

a) ASCII

b) JPEG

c) MPEG

d) ZIP
Answer: a) ASCII

3. Opening and Closing Files

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

a) file_open()

b) open()

c) load()

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

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

17
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

a) Read mode (‘r’)

b) Write mode (‘w’)

c) Append mode (‘a’)

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’

b) ‘w+’

c) ‘a’

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

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

a) The file is opened in read mode

b) The existing content is overwritten

c) The file is deleted

d) An error occurs
Answer: b) The existing content is overwritten

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

a) file.name

b) file.mode

c) file.closed

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

18
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

14. How is a file closed in Python?

a) file.close()

b) close(file)

c) file.exit()

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

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

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

4. Writing to a Text File

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

a) writeline()

b) write()

c) append()

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

17. What does the write() method return?

a) The number of characters written

19
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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?

a) Directly using write()

b) By converting it to a string first

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

b) write()

c) appendlines()

d) insertlines()
Answer: a) writelines()

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

a) To close the file

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

c) To read the file

d) To delete the file


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

20
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

5. Reading from a Text File


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

a) read()

b) readline()

c) readlines()

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

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

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

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

a) read()

b) readline()

c) readlines()

d) load()
Answer: b) readline()

24. What does the readlines() method return?

a) A single string

b) A list of strings

c) A tuple of strings

21
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

c) Using seek() in a loop

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

c) Joins multiple lines

d) Closes the file


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

6. Setting Offsets in a File

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

a) seek()

b) tell()

c) pos()

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

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

22
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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)

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

a) seek(10, 0)

b) seek(0, 10)

c) seek(10, 1)

d) seek(10, 2)
Answer: a) seek(10, 0)

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

23
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

b) ‘w+’

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

b) Using a while loop with readline()

c) Both a and b

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

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

a) The number of lines written

b) The current byte position of the file object

c) The file size

d) The number of characters written


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

8. The Pickle Module

24
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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

a) write()

b) dump()

c) load()

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

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

a) read()

b) load()

c) get()

d) unpickle()
Answer: b) load()

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

a) ‘w’

b) ‘wb’

c) ‘wr’

25
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

39. What happens if a binary file is corrupted?

a) It can be easily fixed

b) It becomes unreadable

c) It automatically repairs itself

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

c) IOError

d) ValueError
Answer: b) EOFError

Miscellaneous

41. What is serialization?

a) Converting Python objects to byte streams

b) Reading text files

c) Writing binary files

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

42. What is deserialization?

26
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

43. Which module is required for pickling and unpickling?

a) io

b) pickle

c) os

d) sys
Answer: b) pickle

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

a) True

b) False

c) 1

d) 0
Answer: b) False

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

a) close()

b) flush()

c) write()

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

27
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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

a) file.name

b) file.mode

c) file.size

d) file.closed
Answer: c) file.size

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

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

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

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

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

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

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

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

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

28
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

c) To create graphical interfaces

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

Answer: A

52. Assertion (A): Binary files can be edited easily using Notepad or any text editor.
Reason (R): Binary files store information using human-readable 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
(C) A is true, but R is false
(D) A is false, but R is true

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

29
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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

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: D

56. Assertion (A): The writelines() method requires a list or tuple of strings.
Reason (R): It adds newline characters between each string automatically.

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

30
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

Answer: C

58. Assertion (A): The read() method reads the complete file when no parameter is passed.
Reason (R): It returns a list of strings when the file is completely read.

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

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.

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

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

31
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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.

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

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.

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

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

32
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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.
Reason (R): The file must be opened in 'rb' mode to use dump().

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
(dump() requires 'wb', not 'rb')

66. Assertion (A): The load() method is used for unpickling data from a binary file.
Reason (R): It recreates the original Python object from the byte stream.

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

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


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

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

33
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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

70. Assertion (A): pickle.load() raises EOFError when end of file is reached.
Reason (R): This helps to read binary files using a while loop and try-except block.

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

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

34
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

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

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

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

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

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

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

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

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’

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

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

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

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

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

35
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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.

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

2. What is the purpose of file modes? Give syntax to open a file in read-write mode.
Answer:
File modes determine operations allowed on a file.
Syntax: file_object = open("filename.txt", "r+")

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

• write(): Writes a single string (file.write("Hello"))

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

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

• ‘w’ mode overwrites existing content.

• ‘a’ mode appends to existing content.

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


Answer:

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

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

36
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• 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:

1. Explicit: file.close()

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

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

import pickle
pickle.dump([1, 2, 3], open("data.dat", "wb"))

9. Explain the purpose of the split() method in file handling with an example.
Answer:
Splits strings into lists.
Example:

line = "Hello World"


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

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:

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

37
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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.

• ‘w’ mode creates a new file.

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


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

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

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

• ‘w’ deletes existing content.

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:

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


for line in f:
print(line)

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

• file.name: Returns filename.

• file.mode: Returns access mode.

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

38
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• 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:

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


• Perform operations (read/write) using appropriate methods
• Close file using close() method to free resources
• Alternatively use with statement for automatic closing

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

• Store human-readable characters


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

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:

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


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

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

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


f.write("First line\n")
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

39
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• 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
• readlines(): Returns list of all lines

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

• Used for object serialization

• dump(): Writes object to file


pickle.dump(obj, file)

• load(): Reads object from file


obj = pickle.load(file)

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

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


for line in f:
if line.startswith('A'):
print(line)

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

• Automatically closes file


• Handles exceptions properly
• Cleaner and more readable code

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

• write(): Accepts single string


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)

40
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• 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:

• file.name: Returns filename


print(file.name)

• file.mode: Returns access mode


print(file.mode)

• file.closed: Returns True if closed


print(file.closed)

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

• 0: Beginning of file (default)


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

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

count = 0
with open("data.txt", "r") as f:
for line in f:
count += 1
print("Total lines:", count)

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

• Frees system resources


• Ensures all data is written
• 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)

41
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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


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

• splitlines(): Splits at line breaks


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

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

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

5 MARKS QUESTIONS

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

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


as file:
• Writing: file.write("Content") or file.writelines(["Line1\n", "Line2\n"])
• Reading: content = file.read() or lines = file.readlines()
• Positioning: pos = file.tell() and file.seek(offset)
• Closing: file.close() (automatic in with statement) Example:
with open("demo.txt", "w+") as f:
f.write("Sample text\n")
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

42
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• 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


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

3. Explain in detail the various file opening modes with their file pointer positions and suitable
use cases. Answer:

Mode Pointer Position Use Case

‘r’ Beginning Read existing files


‘w’ Beginning Create/overwrite files
‘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
‘b’ - Binary mode suffix (e.g., ‘rb’, ‘wb’)

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

import pickle

# Pickling (Serialization)
try:
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:

43
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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:
– name: print(file.name) # Shows filename
– mode: print(file.mode) # Shows access mode
– closed: print(file.closed) # True/False
• Methods:
– 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

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("students.txt", "a") as f:
name = input("Enter name: ")
roll = input("Enter roll no: ")
f.write(f"{roll},{name}\n")

def view_students():
with open("students.txt", "r") as f:
print("\nStudent Records:")
for line in f:
roll, name = line.strip().split(',')
print(f"Roll: {roll}, Name: {name}")

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

44
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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:
while True:
line = f.readline()
if not line: break
print(line)
• Random Access:
– Direct access using positions
– Methods: seek(), tell()
– Example:
with open("random.txt", "rb+") as f:
f.seek(10)
f.write(b"NEWDATA")
print("Current position:", f.tell())

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

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

• Advantages:

1. Preserves object state


2. Enables complex data storage
3. Supports network transmission

• Example:
import pickle

# 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:

45
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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:
f.write("Initial content\n")

# Appending
with open("operations.txt", "a") as f:
f.write("Appended content\n")

# Reading
with open("operations.txt", "r") as f:
print("File content:")
print(f.read())

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
would be appropriate. Answer:

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


with open("data.txt", "r") as f:
content = f.read() # For small files

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


with open("large.txt", "r") as f:
while True:
line = f.readline()
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

46
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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:

# Demonstrate all key file methods


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

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

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

# READ
content = f.read(10) # First 10 chars
print(f"Partial read: {content}")
print(f"After read(10) - Position: {f.tell()}") # 10

# READLINE
f.seek(0)
print("Full content:")
while True:
line = f.readline()
if not line: break
print(line.strip())

12. Compare and contrast the working of text mode vs binary mode file operations with suitable
examples for each.
Answer:

Aspect Text Mode Binary Mode

Data Handling Automatic encoding/decoding Raw bytes

47
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

13. Explain the detailed working of the seek() method with all possible reference points and
practical applications.
Answer:

• Reference Points:

1. 0 (default): Beginning of file

2. 1: Current position

3. 2: End of file

• Applications:

# Jump to beginning
f.seek(0)

# Move 5 bytes forward from current position


f.seek(5, 1)

# Go to 10 bytes before end


f.seek(-10, 2)

# Practical use: Read last line


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:

48
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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
copy_binary_file("original.jpg", "copy.jpg")

CHAPTER END EXERCISES

1. Differentiate between:

a) Text file and binary file


Answer:

• 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:

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

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

c) write() and writelines()


Answer:

• write() accepts a single string argument.

• writelines() accepts an iterable of strings.

49
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

a) open()
Answer:

• Use: To open a file

• Syntax: file_object = open(filename, mode)

b) read()
Answer:

• Use: Reads file content

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

c) seek()
Answer:

• Use: Moves file pointer

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

d) dump()
Answer:

• Use: Writes Python objects to binary files

• Syntax: pickle.dump(object, file_object)

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:

50
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

• Mode: 'r+'

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

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


Answer:

• Mode: 'wb'

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

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


Answer:

• Mode: 'a+'

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

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


Answer:

• Mode: 'rb'

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

4. Why is it advised to close a file after we are done with the read and write operations?
What will happen if we do not close it? Will some error message be flashed? Answer:
- Prevents memory leaks and data corruption.
- Unclosed files may remain locked, preventing other operations.
- No immediate error, but may cause resource issues.

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

a)

51
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

b)

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

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

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”
“You will learn and play”
Answer:

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


f.write("Welcome my class\n")
f.write("It is a fun place\n")
f.write("You will learn and play\n")

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
instead of append mode? Answer:

# Read mode
with open("hello.txt", "r") as f:
print(f.read())

# Write mode would overwrite all content

52
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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

# Display filtered content


with open("output.txt", "r") as f:
for line in f:
if line.strip() and line[0].isupper():
print(line.strip())

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


Answer:
- Pickling: Process of converting Python objects to byte streams.
- Serialization: Object → Byte stream (using pickle.dump()).
- Deserialization: Byte stream → Object (using pickle.load()).

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

Display records in format:


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

Answer:

53
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON

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: "))
price = float(input("Price: "))
pickle.dump([item_no, name, qty, price], f)

# Reading records
with open("items.dat", "rb") as f:
while True:
try:
item = pickle.load(f)
print(f"\nItem No: {item[0]}")
print(f"Item Name: {item[1]}")
print(f"Quantity: {item[2]}")
print(f"Price per item: {item[3]}")
print(f"Amount: {item[2] * item[3]}")
except EOFError:
break

54

You might also like