💻
Chapter 3 · Class 12 Computer Science
File Handling in Python
1 exercises3 questions solved
Exercise 3.1File Handling in Python
Q1
What is file handling in Python? Explain the modes of opening a file. How do you open and close a file?
Solution
File Handling:
• File handling allows Python programs to create, read, write, and manipulate files stored on disk — enabling data to persist beyond the program's execution.
• Python's built-in open() function is used to open files.
Syntax: file_object = open(filename, mode)
File Opening Modes:
1. 'r' (Read — default):
• Opens an existing file for reading only.
• File pointer placed at the beginning.
• Error (FileNotFoundError) if file does not exist.
• Example: f = open('data.txt', 'r')
2. 'w' (Write):
• Opens file for writing only.
• Creates the file if it does not exist.
• If the file exists, it is TRUNCATED (all content erased) before writing.
• Example: f = open('output.txt', 'w')
3. 'a' (Append):
• Opens file for appending — new data is added at the END of the file.
• Creates the file if it does not exist.
• Existing content is NOT erased.
• Example: f = open('log.txt', 'a')
4. 'r+' (Read and Write):
• Opens existing file for both reading and writing.
• Does not truncate; file must exist.
5. 'w+' (Write and Read):
• Opens file for reading and writing; truncates if exists.
6. 'a+' (Append and Read):
• Opens for reading and appending.
7. 'b' (Binary mode — combined with other modes):
• Opens file in binary mode (for images, audio, PDFs, etc.)
• Example: 'rb' (read binary), 'wb' (write binary)
Opening and Closing:
# Method 1: Explicit open and close
f = open('data.txt', 'r')
content = f.read()
f.close() # Always close to release resources
# Method 2: with statement (recommended — auto-closes)
with open('data.txt', 'r') as f:
content = f.read()
# File is automatically closed when the with block exits
The with statement is preferred because it ensures the file is closed even if an exception occurs.
Q2
Explain the methods available for reading from and writing to a text file in Python with examples.
Solution
Reading Methods:
1. read(size=-1):
• Reads the entire file content as a single string (if size not specified).
• If size is specified, reads that many characters.
with open('data.txt', 'r') as f:
content = f.read() # entire file
content = f.read(100) # first 100 chars
2. readline():
• Reads one line at a time (including the '\n' newline character).
• Returns an empty string ('') when end of file is reached.
with open('data.txt', 'r') as f:
line = f.readline() # reads first line
while line:
print(line, end='')
line = f.readline()
3. readlines():
• Reads all lines and returns them as a list of strings.
with open('data.txt', 'r') as f:
lines = f.readlines() # e.g., ['Hello\n', 'World\n']
4. Iterating directly (most Pythonic):
with open('data.txt', 'r') as f:
for line in f:
print(line, end='')
Writing Methods:
1. write(string):
• Writes a string to the file.
• Does NOT add a newline automatically — you must include '\n' if needed.
• Returns the number of characters written.
with open('output.txt', 'w') as f:
f.write('Hello, World!\n')
f.write('Second line\n')
2. writelines(list_of_strings):
• Writes a list of strings to the file.
• Does NOT add newlines — include '\n' in each string if needed.
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w') as f:
f.writelines(lines)
File Pointer Methods:
• tell(): Returns current position of the file pointer (byte offset from start).
• seek(offset, from_what=0): Moves the file pointer.
- seek(0) — move to beginning
- seek(0, 2) — move to end
Q3
What are CSV files? How do you read from and write to a CSV file using Python's csv module?
Solution
CSV (Comma-Separated Values):
• A CSV file is a plain text file that stores tabular data — each row is a line of text, and values in each row are separated by commas (or another delimiter).
• CSV files are widely used for data exchange between applications (spreadsheets, databases, data science tools).
• Example CSV content (students.csv):
RollNo,Name,Marks
1,Priya,92
2,Arjun,85
3,Meena,78
Python's csv Module:
• Python's standard library includes the csv module for easy reading/writing of CSV files.
Writing a CSV File:
import csv
data = [
['RollNo', 'Name', 'Marks'],
[1, 'Priya', 92],
[2, 'Arjun', 85],
[3, 'Meena', 78]
]
with open('students.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data) # writes all rows at once
# OR: writer.writerow(row) to write one row at a time
# Note: newline='' prevents extra blank lines on Windows.
Reading a CSV File:
import csv
with open('students.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row) # each row is a list of strings
# Output:
# ['RollNo', 'Name', 'Marks']
# ['1', 'Priya', '92']
# ['2', 'Arjun', '85']
Using DictReader and DictWriter (more readable):
# DictReader — reads rows as dictionaries (keys = header column names)
with open('students.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['Name'], row['Marks'])
# Output: Priya 92, Arjun 85 ...
# DictWriter — writes from list of dictionaries
import csv
fields = ['RollNo', 'Name', 'Marks']
rows = [{'RollNo': 1, 'Name': 'Priya', 'Marks': 92}]
with open('students.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader() # writes the header row
writer.writerows(rows)
More chapters
← All chapters: Class 12 Computer Science