File Handling in Python - Answers
Qn 1. File Access Modes in Python (16 marks)
Python uses file access modes to control how a file is opened and manipulated. Here's a summary:
Mode | Description
------|-------------
'r' | Read: Opens file for reading. File must exist.
'w' | Write: Creates new file or truncates existing.
'a' | Append: Adds data at end of file. Creates file if it doesn't exist.
'x' | Exclusive creation: Creates new file. Fails if file exists.
'b' | Binary mode: For non-text files like images or audio.
't' | Text mode: Default; used for reading/writing text.
'r+' | Read + Write: File must exist.
'w+' | Write + Read: Overwrites existing or creates new.
'a+' | Append + Read: Allows reading and appending.
Examples:
# Example 1: Write Mode ('w')
with open("file_w.txt", "w") as file:
[Link]("This file is written using 'w' mode.\n")
# Example 2: Read Mode ('r')
with open("file_w.txt", "r") as file:
content = [Link]()
print("Content of file:", content)
# Example 3: Append Mode ('a')
with open("file_w.txt", "a") as file:
[Link]("Adding this line using 'a' mode.\n")
Qn 2. File Object Methods (8 marks)
a) read(): Reads the entire content of the file.
with open("file_w.txt", "r") as f:
data = [Link]()
print(data)
b) readline(): Reads one line at a time.
with open("file_w.txt", "r") as f:
line = [Link]()
print("First line:", line)
c) tell(): Returns the current position of the file pointer.
with open("file_w.txt", "r") as f:
print("Position at start:", [Link]())
File Handling in Python - Answers
[Link](5)
print("Position after 5 chars:", [Link]())
d) write(): Writes a string to the file.
with open("[Link]", "w") as f:
[Link]("This is written using write().")
Qn 3. Program to Check Number in File (8 marks)
Sample content of [Link]:
10 25 30 45 50 75
Python Program:
filename = "[Link]"
# Read numbers from the file
with open(filename, "r") as f:
content = [Link]()
numbers = list(map(int, [Link]()))
# Ask user for a number
target = int(input("Enter number to search: "))
# Check if number is in list
if target in numbers:
print(f"{target} is present in the list.")
else:
print(f"{target} is NOT present in the list.")