Chap 2 File Handling in Python
Chap 2 File Handling in Python
Contents
LICENSE 4
2
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
2 MARKS QUESTIONS 36
3 MARKS QUESTIONS 39
5 MARKS QUESTIONS 42
3
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
STUDENT NOTES || 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
Text Files
Example:
Binary Files
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:
Read Mode - r
f = open("myfile.txt", "r")
f = open("myfile.txt", "rb")
f = open("myfile.txt", "r+")
Write Mode - w
f = open("myfile.txt", "w")
f = open("myfile.txt", "wb+")
6
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Append Mode - a
f = open("myfile.txt", "a")
f = open("myfile.txt", "a+")
File Attributes
Closing a File
file_object.close()
7
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Example:
File Attributes
Closing a File
Syntax:
file_object.close()
Syntax:
8
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Syntax: write()
file_object.write(string)
Example: write()
Writing numbers:
marks = 58
myobject.write(str(marks))
Syntax: writelines()
file_object.writelines(list_of_strings)
Example: writelines()
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
Syntax: read(n)
file_object.read(n)
Example: read(n)
Syntax: read()
file_object.read()
Example: read()
Syntax: readline(n)
file_object.readline(n)
Example: readline(n)
10
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Syntax: readlines()
file_object.readlines()
Example: readlines()
Using splitlines():
11
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Syntax: tell()
file_object.tell()
file_object.tell()
file_object.seek(offset, reference_point)
• Moves pointer to specified position from reference point (0 = start, 1 = current, 2 = end).
Program Example:
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()
Pickle Module
Pickling
Unpickling
13
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
Import Statement
import pickle
pickle.dump(object, file_object)
variable = pickle.load(file_object)
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
1. Introduction to Files
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
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
a) \r
b) \n
c) \t
d) \0
Answer: b) \n
a) ASCII
b) JPEG
c) MPEG
d) ZIP
Answer: a) ASCII
a) file_open()
b) open()
c) load()
d) read()
Answer: b) open()
17
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
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+’
d) An error occurs
Answer: b) The existing content is overwritten
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
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) writeline()
b) write()
c) append()
d) insert()
Answer: b) write()
19
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
d) None
Answer: a) The number of characters written
d) It cannot be written
Answer: b) By converting it to a string first
a) writelines()
b) write()
c) appendlines()
d) insertlines()
Answer: a) writelines()
20
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
a) read()
b) readline()
c) readlines()
d) seek()
Answer: a) read()
c) It returns an error
d) It reads 10 bytes
Answer: b) It reads the entire file
a) read()
b) readline()
c) readlines()
d) load()
Answer: b) readline()
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?
27. Which method returns the current position of the file object?
a) seek()
b) tell()
c) pos()
d) offset()
Answer: b) tell()
22
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
29. What is the default reference point for the seek() method?
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)
31. What happens if a file opened in ‘a’ mode does not exist?
a) An error occurs
23
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
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+’
c) Both a and b
d) Using seek()
Answer: c) Both a and b
24
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
d) To compress files
Answer: b) To serialize and deserialize Python objects
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()
a) ‘w’
b) ‘wb’
c) ‘wr’
25
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
d) ‘w+’
Answer: b) ‘wb’
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
d) Closing files
Answer: a) Converting Python objects to byte streams
26
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
d) Opening files
Answer: a) Converting byte streams to Python objects
a) io
b) pickle
c) os
d) sys
Answer: b) pickle
a) True
b) False
c) 1
d) 0
Answer: b) False
a) close()
b) flush()
c) write()
d) dump()
Answer: b) flush()
27
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
d) To close a file
Answer: b) To split a string into a list of lines
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”)
28
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
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
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
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
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
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
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+’
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
• 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:
4. What happens when a file is opened in ‘w’ mode versus ‘a’ mode?
Answer:
36
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
1. Explicit: file.close()
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:
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:
14. What happens if you open a non-existent file in ‘r’ mode versus ‘w’ mode?
Answer:
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.
19. What are the attributes of a file object? Mention any two.
Answer:
20. Differentiate between dump() and load() methods of the pickle module.
Answer:
38
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
3 MARKS QUESTIONS
1. Explain the file handling process in Python with proper steps. Answer:
2. Differentiate between text and binary files with three points each. Answer: Text Files:
Binary Files:
4. Write a Python program to create a file and write three lines of text to it.
5. Explain the working of seek() and tell() methods with examples. Answer:
39
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
7. Explain the pickle module with its two main methods and syntax. Answer:
8. Write a program to read a file and display lines starting with ‘A’.
9. Explain three advantages of using ‘with’ statement for file handling. Answer:
10. Differentiate between write() and writelines() methods with examples. Answer:
40
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
14. What are the different reference points in seek() method? Explain. Answer:
count = 0
with open("data.txt", "r") as f:
for line in f:
count += 1
print("Total lines:", count)
17. Differentiate between ‘r+’, ‘w+’ and ‘a+’ file modes. Answer:
41
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
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:
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:
2. Compare and contrast text files and binary files with respect to: storage format, readability,
extensions, and use cases. Answer:
42
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
3. Explain in detail the various file opening modes with their file pointer positions and suitable
use cases. Answer:
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
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:
• Advantages:
• 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:
46
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
11. Create a comprehensive program that demonstrates all file object methods (read, write,
seek, tell, flush) with proper documentation.
Answer:
# 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:
47
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
13. Explain the detailed working of the seek() method with all possible reference points and
practical applications.
Answer:
• Reference Points:
2. 1: Current position
3. 2: End of file
• Applications:
# Jump to beginning
f.seek(0)
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
# Usage
copy_binary_file("original.jpg", "copy.jpg")
1. Differentiate between:
• 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.
49
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
a) open()
Answer:
b) read()
Answer:
c) seek()
Answer:
d) dump()
Answer:
3. Write the file mode that will be used for opening the following files. Also, write the
Python statements to open the following files:
50
STUDENT NOTES || CHAPTER 2 FILE HANDLING IN PYTHON
• Mode: 'r+'
• Mode: 'wb'
• Mode: 'a+'
• Mode: '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:
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())
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:
10. Write a program to enter the following records in a binary file: Item No (integer)
Item_Name (string)
Qty (integer)
Price (float)
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