Chapter 7 File Handling
Q1] Check Your Progress
Q1. Which mode is used to open a file in reading mode?
✅ Answer: 'r' (read mode)
Q2. Which mode is used to open a file in write mode?
✅ Answer: 'w' (write mode)
Q3. Which mode is used to open a file in append mode?
✅ Answer: 'a' (append mode)
Q2] What are Files in Python and Their Uses?
✅ Answer:
1. A file is a place on the disk where data is stored permanently.
2. In Python, files are used to store and retrieve data even after a program ends.
3. You can read, write, append, or modify files easily using Python.
4. Files are used for:
Saving user data
Reading configuration
Generating reports
Data analysis
Q3] Explain Different File Modes Available in Python
Mode Meaning Description
'r' Read Opens file for reading (error if file doesn’t exist).
'w' Write Opens file for writing (creates new file or overwrites existing).
'a' Append Opens file for writing and appends data at the end.
'r+' Read + Write Opens file for both reading and writing.
'w+' Write + Read Overwrites file and allows reading.
'a+' Append + Read Appends to file and allows reading.
Mode Meaning Description
'b' Binary Used for binary files (images, videos).
't' Text Default mode for reading/writing text files.
Q4] Write a Python Program to Read an Entire Text
File
# Program to read an entire file
file = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()
Q5] Write a Python Program to Read First n Lines of a
File
# Program to read first n lines
n = int(input("Enter number of lines to read: "))
file = open("[Link]", "r")
for i in range(n):
line = [Link]()
print(line, end='')
[Link]()
Q6] Write a Python Program to Append Text to a File
and Display the Text
# Program to append text and display file
file = open("[Link]", "a")
[Link]("\nThis is new text added.")
[Link]()
# Display the updated file content
file = open("[Link]", "r")
print([Link]())
[Link]()
Q7] Write a Python Program to Read Last n Lines of a
File
# Program to read last n lines
n = int(input("Enter number of lines from end: "))
file = open("[Link]", "r")
lines = [Link]()
for line in lines[-n:]:
print(line, end='')
[Link]()
✅ Extra Tip for Exams:
Always remember to close files using [Link]() after operations —
or use with open() statement (it closes automatically).
Example:
with open("[Link]", "r") as f:
data = [Link]()
print(data)