Chapter 2 File Handling in Python
Chapter 2 File Handling in Python
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
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
Example: write() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Syntax: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Example: writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
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
R
Syntax for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
L
Syntax for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Example for dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
N
Example for load() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
EE
Complete Program Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3 MARKS QUESTIONS 39
5 MARKS QUESTIONS 42
ED
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
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
Example:
Binary Files
M
A
Opening a File
• Files are opened using the open() function which returns a file object.
Syntax:
Read Mode - r
R
• File must exist.
L
• File pointer at the beginning.
f = open("myfile.txt", "r")
N
EE
Binary Read Mode - rb
f = open("myfile.txt", "rb") H
AT
Read and Write Mode - r+
M
f = open("myfile.txt", "r+")
M
Write Mode - w
M
f = open("myfile.txt", "w")
O
f = open("myfile.txt", "wb+")
Append Mode - a
f = open("myfile.txt", "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
Closing a File
M
file_object.close()
M
A
content = myObject.read()
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
Closing a File
M
Syntax:
A
file_object.close()
H
O
Syntax:
Syntax: write()
file_object.write(string)
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
Example: writelines()
A
H
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
myobject.writelines(lines)
M
Syntax: read(n)
file_object.read(n)
R
Example: read(n)
L
• Reads n bytes from the file.
N
print(myobject.read(10))
EE
myobject.close()
Syntax: read()
H
AT
file_object.read()
Example: read()
ED
print(myobject.read())
M
myobject.close()
A
Syntax: readline(n)
H
file_object.readline(n)
O
Example: readline(n)
Syntax: readlines()
file_object.readlines()
Example: readlines()
R
• Reads all lines and returns a list.
L
print(myobject.readlines())
N
myobject.close()
EE
Splitting into words:
fobject.write(sentence)
fobject.close()
A
fobject.close()
Syntax: tell()
file_object.tell()
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).
Program Example:
M
print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
M
fileobject.close()
H
O
M
fileobject.write(data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n': break
fileobject.close()
R
str = fileobject.readline()
while str:
L
print(str)
str = fileobject.readline()
N
fileobject.close()
EE
Combined Read/Write Program
print(fileobject.read())
fileobject.close()
M
A
H
Pickle Module
O
Pickling
M
Unpickling
Import Statement
import pickle
pickle.dump(object, file_object)
R
Syntax for load()
L
variable = pickle.load(file_object)
N
EE
Example for dump()
print(objectvar)
M
import pickle
H
while True:
M
R
except EOFError:
pass
L
N
MULTIPLE CHOICE QUESTIONS (MCQ)
EE
1. Introduction to Files
c) CPU registers
M
d) Cache memory
Answer: b) Secondary storage media
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
a) A .csv file
b) A .py file
c) A .docx file
d) A .txt file
Answer: c) A .docx file
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
a) file_open()
O
b) open()
M
c) load()
d) read()
Answer: b) open()
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
d) An error occurs
A
a) file.name
M
b) file.mode
c) file.closed
d) file.size
Answer: b) file.mode
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
a) writeline()
A
b) write()
H
O
c) append()
M
d) insert()
Answer: b) write()
d) None
Answer: a) The number of characters written
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()
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
d) It reads 10 bytes
Answer: b) It reads the entire file
ED
a) read()
M
b) readline()
M
A
c) readlines()
H
d) load()
O
Answer: b) readline()
M
a) A single string
b) A list of strings
c) A tuple of strings
d) A dictionary of strings
Answer: b) A list of strings
25. How can you read a file line by line using a 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?
H
AT
b) Splits each line into a list of words
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()
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
31. What happens if a file opened in ‘a’ mode does not exist?
a) An error occurs
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+’
c) Both a and b
ED
d) Using seek()
Answer: c) Both a and b
M
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
a) ‘w’
b) ‘wb’
c) ‘wr’
d) ‘w+’
Answer: b) ‘wb’
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
d) Closing files
Answer: a) Converting Python objects to byte streams
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
a) True
ED
b) False
M
c) 1
M
d) 0
A
Answer: b) False
H
a) close()
M
b) flush()
c) write()
d) dump()
Answer: b) flush()
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
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
Answer: A
ED
M
52. Assertion (A): Binary files can be edited easily using Notepad or any text editor.
M
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
Answer: D
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
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
Answer: D
M
A
56. Assertion (A): The writelines() method requires a list or tuple of strings.
H
Options:
M
Answer: C
57. Assertion (A): Opening a file in 'w' mode erases its existing contents.
Reason (R): In this mode, the file pointer is placed at the end of the file.
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
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
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
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
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
(B) Both A and R are true, but R is not the correct explanation of A
M
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.
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
Answer: A
A
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.)
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
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
Answer: A
M
1. A file is a named location on ________ storage media where data is permanently stored. Answer:
secondary
2. The two main types of files are ________ files and binary files. Answer: text
3. Text files store data using ________ or Unicode encoding schemes. Answer: ASCII
5. Binary files store data in ________ format that is not human-readable. Answer: byte
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()
2 MARKS QUESTIONS
• 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
4. What happens when a file is opened in ‘w’ mode versus ‘a’ mode?
Answer:
M
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
Answer:
Automatically closes files after block execution, even if errors occur.
H
Answer:
M
12. What is serialization? Name the Python module used for it.
Answer:
Process of converting objects to byte streams. Module: pickle.
13. Give syntax to load data from a binary file using pickle.
Answer:
14. What happens if you open a non-existent file in ‘r’ mode versus ‘w’ mode?
Answer:
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
Answer:
A
print(line)
O
19. What are the attributes of a file object? Mention any two.
M
Answer:
20. Differentiate between dump() and load() methods of the pickle module.
Answer:
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:
Binary Files:
M
4. Write a Python program to create a file and write three lines of text to it.
O
f.write("Second line\n")
f.write("Third line\n")
5. Explain the working of seek() and tell() methods with examples. Answer:
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)
8. Write a program to read a file and display lines starting with ‘A’.
M
if line.startswith('A'):
print(line)
M
9. Explain three advantages of using ‘with’ statement for file handling. Answer:
10. Differentiate between write() and writelines() methods with examples. Answer:
O
file.write("Hello")
R
• file.name: Returns filename
L
print(file.name)
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:
• 1: Current position
• 2: End of file Example: file.seek(5, 0) moves to 5th byte from start
ED
count = 0
M
count += 1
print("Total lines:", count)
A
17. Differentiate between ‘r+’, ‘w+’ and ‘a+’ file modes. Answer:
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:
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
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:
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
4. Demonstrate the complete process of pickling and unpickling with proper error handling.
Answer:
A
import pickle
H
O
# Pickling (Serialization)
try:
M
# Unpickling (Deserialization)
try:
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
def view_students():
M
for line in f:
H
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")
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
8. Explain the concept of serialization with its advantages and demonstrate using the pickle
ED
module. Answer:
• Advantages:
M
• 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:
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
while True:
line = f.readline()
M
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
# READLINE
f.seek(0)
M
print("Full content:")
while True:
A
line = f.readline()
H
12. Compare and contrast the working of text mode vs binary mode file operations with suitable
M
R
13. Explain the detailed working of the seek() method with all possible reference points and
L
practical applications.
Answer:
N
EE
• Reference Points:
3. 2: End of file
ED
• Applications:
# Jump to beginning
M
f.seek(0)
M
14. Develop a program that demonstrates reading a binary file (like an image) and creating its
copy.
Answer:
# Usage
R
copy_binary_file("original.jpg", "copy.jpg")
L
CHAPTER END EXERCISES
N
EE
1. Differentiate between:
• Binary files store data as bytes (0s/1s) for non-text data like images/audio with extensions like .dat,
ED
.jpg.
Answer:
M
a) open()
Answer:
R
b) read()
L
Answer:
N
EE
• Use: Reads file content
c) seek() H
AT
Answer:
M
d) dump()
M
Answer:
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:
• Mode: 'r+'
• 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+")
Answer:
ED
• Mode: 'rb'
M
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
5. What is the difference between the following set of statements (a) and (b):
a)
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
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
# Read mode
O
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:
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
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
Item Name:
Quantity:
Price per item:
Amount: (Price * Qty)
Answer:
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
https://matheenhere.blogspot.com
M
A
H
O
M