File Handling in Python - Answers
Qn 1. File Access Modes in Python (16 marks)
Python provides several file access modes, allowing developers to handle files in various ways such as reading, writing,
appending, and modifying both text and binary files. These modes are specified as strings when using the `open()`
function.
Here are the commonly used file access modes in Python:
1. 'r' ' Read Mode:
- Opens a file for reading only.
- File must exist.
- If the file doesn't exist, Python raises a FileNotFoundError.
2. 'w' ' Write Mode:
- Opens a file for writing.
- Creates the file if it does not exist.
- Truncates (deletes) existing file content if the file already exists.
3. 'a' ' Append Mode:
- Opens a file for writing.
- Creates the file if it doesn't exist.
- Does not truncate the file, instead appends content at the end.
4. 'x' ' Exclusive Creation:
- Creates a new file.
- Raises FileExistsError if the file already exists.
- Used to prevent overwriting files by accident.
5. 'b' ' Binary Mode:
- Used in combination with other modes (e.g., 'rb', 'wb') to read/write binary files like images or executables.
- Data is handled in bytes.
6. 't' ' Text Mode:
- Default mode for text files.
- Files are read and written in terms of strings.
7. 'r+' ' Read and Write Mode:
- Opens the file for both reading and writing.
- File must exist. Pointer starts at the beginning of the file.
8. 'w+' ' Write and Read Mode:
- Opens the file for reading and writing.
- Truncates existing content or creates a new file.
9. 'a+' ' Append and Read Mode:
- Opens the file for both appending and reading.
- File pointer is at the end if writing but can be moved for reading.
File Handling in Python - Answers
--- Examples ---
# Example 1: Write Mode ('w')
with open("file_w.txt", "w") as file:
file.write("This file is written using 'w' mode.\n")
# This will overwrite file_w.txt or create it if it doesn't exist.
# Example 2: Read Mode ('r')
with open("file_w.txt", "r") as file:
content = file.read()
print("Content of file:", content)
# Useful when we want to read the file content safely.
# Example 3: Append Mode ('a')
with open("file_w.txt", "a") as file:
file.write("Adding this line using 'a' mode.\n")
# This keeps previous content intact and adds more lines at the end.
Summary:
File modes allow controlled operations with files. By selecting the correct mode, developers can efficiently handle file
input/output operations, ensuring that data is safely read, written, or appended. Binary modes enable working with
media and other non-text files, while text modes are used for standard reading/writing of strings.
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 = f.read()
print(data)
b) readline(): Reads one line at a time.
with open("file_w.txt", "r") as f:
line = f.readline()
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:", f.tell())
f.read(5)
print("Position after 5 chars:", f.tell())
d) write(): Writes a string to the file.
with open("output.txt", "w") as f:
f.write("This is written using write().")
File Handling in Python - Answers
Qn 3. Program to Check Number in File (8 marks)
Sample content of numbers.txt:
10 25 30 45 50 75
Python Program:
filename = "numbers.txt"
# Read numbers from the file
with open(filename, "r") as f:
content = f.read()
numbers = list(map(int, content.split()))
# 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.")