0% found this document useful (0 votes)
14 views13 pages

File Handling Q&A

The document outlines various file types in Python, including text, CSV, and binary files, along with their handling methods. It covers core concepts such as file opening modes, reading and writing techniques, and examples of using the csv and pickle modules. Additionally, it includes practical code snippets for common tasks like filtering records, counting lines, and modifying file contents.

Uploaded by

spamyaue
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

File Handling Q&A

The document outlines various file types in Python, including text, CSV, and binary files, along with their handling methods. It covers core concepts such as file opening modes, reading and writing techniques, and examples of using the csv and pickle modules. Additionally, it includes practical code snippets for common tasks like filtering records, counting lines, and modifying file contents.

Uploaded by

spamyaue
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Types of Files in Python

●​ Text Files (.txt)​

○​ Use basic file I/O methods: open(), read(), readlines(), write(), close().​

○​ Text manipulation: Replace, search, and count words/lines.​

●​ CSV Files (.csv)​

○​ Use the csv module: csv.writer(), csv.reader().​

○​ Requires correct file modes: 'a' for append, 'r' for reading.​

○​ Common methods: writerow() and reader() to process rows as lists.​

●​ Binary Files (.dat)​

○​ Use pickle module: pickle.dump(), pickle.load().​

○​ Files are opened in 'wb', 'ab', or 'rb' modes.​

○​ Stores and retrieves complex Python objects (like lists or dictionaries).

Core Concepts and Skills – With Code Examples

📌 1. File Opening Modes


Mode Description Sample Code

'r' Read (file must exist) f = open("data.txt", "r")

'w' Write (overwrites file or creates new one) f = open("data.txt", "w")

'a' Append to file f = open("data.txt", "a")

'rb' Read in binary mode f = open("data.dat", "rb")

'wb' Write in binary mode f = open("data.dat", "wb")

'ab' Append in binary mode f = open("data.dat", "ab")


📌 2. Reading & Writing Text Files
✅ Reading
# Read full content
with open("story.txt", "r") as f:
content = f.read()
print(content)

✅ Reading Line by Line


with open("story.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())

✅ Writing
with open("story.txt", "w") as f:
f.write("This is a new line.\n")

✅ Appending
with open("story.txt", "a") as f:
f.write("Adding more content.\n")

📌 3. Using csv Module (Text File with Structure)


✅ Writing to CSV
import csv

with open("users.csv", "a", newline='') as f:


writer = csv.writer(f)
writer.writerow(["Name", "Email"])

✅ Reading from CSV


import csv

with open("users.csv", "r") as f:


reader = csv.reader(f)
for row in reader:
print("Name:", row[0], "| Email:", row[1])
📌 4. Using pickle Module (Binary File Handling)
✅ Writing to Binary File
import pickle

data = {"name": "John", "age": 17}


with open("student.dat", "wb") as f:
pickle.dump(data, f)

✅ Reading from Binary File


import pickle

with open("student.dat", "rb") as f:


record = pickle.load(f)
print(record["name"], record["age"])

📌 5. Looping Through Records & Conditions


✅ Example: Filter CSV
import csv

with open("scores.csv", "r") as f:


reader = csv.reader(f)
for row in reader:
if int(row[1]) > 80:
print("Topper:", row[0])

✅ Example: Filter Binary File


import pickle

with open("patients.dat", "rb") as f:


try:
while True:
patients = pickle.load(f)
for p in patients:
if p[2] == "COVID-19":
print("Patient:", p)
except EOFError:
pass
Common Tasks in File Handling
Replace Words in Text Files​

text = file.read()
updated = text.replace('he', 'she')

Count Lines in a Text File​



lines = file.readlines()
print(len(lines))

Filter Records Based on Conditions​



if record[2] > 500: print(record)

Add and Read from CSV​



csv.writer(f).writerow([user, password])
for row in csv.reader(f): print(row)

Count Specific Entries in Binary File​



python​
CopyEdit​
if record[2] == 'COVID-19': count += 1
From Section A (1 Mark MCQs)
Question 10​
Write the missing statement to complete the following code:

file = open("example.txt", "r")


data = file.read(100)
____________________ # Move the file pointer to the beginning of the
file
next_data = file.read(50)
file.close()

✅ Answer: file.seek(0) (OR file.seek(0,0))


🔹 From Section C (3 Marks)
Question 29A​
Write a Python function that displays all the words containing @cmail from a text file


"Emails.txt".
Answer:

def show():
f = open("Email.txt", 'r')
data = f.read()
words = data.split()
for word in words:
if '@cmail' in word:
print(word, end=' ')
f.close()

Question 29B​
Write a Python function that finds and displays all the words longer than 5 characters from a


text file "Words.txt".
Answer:

def display_long_words():
with open("Words.txt", 'r') as file:
data = file.read()
words = data.split()
for word in words:
if len(word) > 5:
print(word, end=' ')
🔹 From Section D (4 Marks)
Question 33
The CSV file "Happiness.csv" contains:
●​ Country Name
●​ Population
●​ Sample Size
●​ Number of Happy People
Part I: Display records with population > 5,000,000



Answer:

def show():
import csv
f = open("happiness.csv", 'r')
records = csv.reader(f)
next(records, None) # To skip the Header row
for i in records:
if int(i[1]) > 5000000:
print(i)
f.close()
Part II: Count the number of records



Answer:

def Count_records():
import csv
f = open("happiness.csv", 'r')
records = csv.reader(f)
next(records, None)
count = 0
for i in records:
count += 1
print(count)
f.close()

🔹 From Section E (5 Marks)


Question 36: Binary file handling using pickle
Part I: Input and append candidate data



Answer:
import pickle

def input_candidates():
candidates = []
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = int(input("Enter Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years): "))
candidates.append([candidate_id, candidate_name, designation,
experience])
return candidates

candidates_list = input_candidates()

def append_candidate_data(candidates):
with open('candidates.bin', 'ab') as file:
for candidate in candidates:
pickle.dump(candidate, file)
print("Candidate data appended successfully.")


Part II: Update designation to “Senior Manager” if experience > 10​
Answer:
def update_senior_manager():
updated_candidates = []
try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[3] > 10:
candidate[2] = 'Senior Manager'
updated_candidates.append(candidate)
except EOFError:
break
except FileNotFoundError:
print("No candidate data found.")
return

with open('candidates.bin', 'wb') as file:


for candidate in updated_candidates:
pickle.dump(candidate, file)

print("Candidates updated.")

Part III: Display non-Senior Managers​
Answer:
def display_non_senior_managers():
try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[2] != 'Senior Manager':
print(f"Candidate ID: {candidate[0]}")
print(f"Candidate Name: {candidate[1]}")
print(f"Designation: {candidate[2]}")
print(f"Experience: {candidate[3]}")
print("--------------------")
except EOFError:
break
except FileNotFoundError:
print("No candidate data found.")

✅ Section A – Objective Type (1 Mark)


Q16:​
Consider the following Python statement:
python
CopyEdit
F = open('CONTENT.TXT')
Which of the following is an invalid statement in Python?
Options:​
(a) F.seek(1,0)​
(b) F.seek(0,1)​
(c) F.seek(0,-1)​

✅📝
(d) F.seek(0,2)
Answer: (c) F.seek(0,-1)​
This is invalid because negative offset with mode 0 (absolute) is not allowed.

Q17 (Assertion/Reason):​
Assertion (A): CSV file is a human-readable text file where each line has a number of fields,
separated by comma or some other delimiter.​

✅Reason (R): writerow() method is used to write a single row in a CSV file.
Answer: (b) Both A and R are true, and R is not the correct explanation for A.

✅ Section C – 3 Marks
Q28 (A):​
Write a Python function showInLines() that reads content from a text file STORY.TXT and
displays each sentence on a new line.​
A sentence ends with ., ?, or !.
✅ Answer (Sample):
def showInLines():
with open("STORY.TXT", 'r') as F:
S = F.read()
for W in S:
if W in ".!?":
print(W)
elif W == "\n":
continue
else:
print(W, end="")

Q28 (B):​
Write a function c_words() in Python that counts and displays the number of uppercase and


lowercase letters in a file Words.txt.
Answer (Sample):
def c_words():
with open("Words.txt", "r") as f:
text = f.read()
CL = CU = 0
for ch in text:
if ch.islower():
CL += 1
elif ch.isupper():
CU += 1
print(CL, CU)

✅ Section D – 4 Marks
Q32:​
A CSV file "Peripheral.csv" has records [P_id, P_name, Price].​
Write:
(i) Add_Device(): to input a record and append it to the file.​

✅(ii) Count_Device(): to count devices with Price < 1000.


Answer (Sample):
import csv

def Add_Device():
with open("Peripheral.csv", "a", newline='') as f:
writer = csv.writer(f)
P_id = int(input("Enter ID: "))
P_name = input("Enter Name: ")
Price = int(input("Enter Price: "))
writer.writerow([P_id, P_name, Price])
def Count_Device():
with open("Peripheral.csv", "r") as f:
reader = csv.reader(f)
count = 0
for row in reader:
if int(row[2]) < 1000:
count += 1
print(count)

✅ Section E – 5 Marks
Q34 (A)(ii):​
A binary file items.dat has records {item_id: [item_name, amount]}.​
Write a function Copy_new() that copies records with amount > 1000 into


new_items.dat.
Answer (Sample):
import pickle

def Copy_new():
with open("items.dat", "rb") as fin, open("new_items.dat", "wb")
as fout:
try:
data = pickle.load(fin)
new_data = {k: v for k, v in data.items() if v[1] > 1000}
pickle.dump(new_data, fout)
except EOFError:
pass

Q34 (B)(ii):​
Binary file EMP.DAT has records: [Emp_Id, Name, Salary].​


Write disp_Detail() to display details of employees with Salary < 25000.
Answer (Sample):
import pickle

def disp_Detail():
try:
with open("EMP.DAT", "rb") as f:
while True:
try:
data = pickle.load(f)
for record in data:
if record[2] < 25000:
print(record)
except EOFError:
break
except FileNotFoundError:
print("File Not Found!")

✅ 2021 CBSE Board Exam – File Handling Questions & Answers


📄 Case Study: CSV File Creation and Reading (Question 23)
Roshni is writing a Python program to create and read from a CSV file Teachers.csv.

✅ Answer: csv or import csv as CSV


Q23(a): Name the module she will import in Line 1.​


Q23(b): Mode to open the file to add data in Line 2.​
Answer: 'a' or 'a+' or 'append'


Q23(c): Mode to open the file to read data in Line 3.​
Answer: 'r' or 'r+' or 'read'

✅ Answer: reader → csv.reader(f)


Q23(d): Fill in the blank in Line 4 to read the data.​

✅ Answer: close()
Q23(e): Fill in the blank in Line 5 to close the file.​

📄 Question 35: Text File Replacement or Line Counting


Option A – ChangeGender() function:​


Replace every "he" with "she" in "BIOPIC.TXT".
Answer:
python
CopyEdit
def ChangeGender():
f = open("BIOPIC.TXT", 'r')
Text = f.read()
print(Text.replace(' he ', ' she '))
f.close()

Option B – Count_Line() function:​


Count total number of lines in "SHIVAJI.TXT".
Answer:
python
CopyEdit
def Count_Line():
f = open("SHIVAJI.TXT", 'r')
Lines = f.readlines()
print('Total number of lines :', len(Lines))
f.close()
📄 Question 40: Binary File Handling – PLANTS.dat

(a) WRITEREC() – To write records to a binary file.
Answer:
python
CopyEdit
import pickle

def WRITEREC():
f = open("PLANTS.dat", "wb")
data_log = []
while True:
ID = int(input("Enter ID:"))
NAME = input("Enter Name:")
PRICE = float(input("Enter Price:"))
data_log.append([ID, NAME, PRICE])
Choice = input("Add more? (Yes/No): ")
if Choice.lower().startswith('n'):
break
pickle.dump(data_log, f)
f.close()


(b) SHOWHIGH() – To display records with PRICE > 500.
Answer:
python
CopyEdit
def SHOWHIGH():
import pickle
f = open("PLANTS.dat", "rb")
try:
while True:
data = pickle.load(f)
for record in data:
if record[2] > 500:
print("ID:", record[0])
print("Name:", record[1])
print("Price:", record[2])
print()
except:
f.close()
📄 Alternative Option in Q40: PATIENTS.dat – countrec()


Function to display and count records where disease is 'COVID-19'
Answer:
python
CopyEdit
import pickle

def countrec():
f = open("PATIENTS.dat", "rb")
N = 0
try:
while True:
data = pickle.load(f)
for record in data:
if record[2] == 'COVID-19':
print("PID:", record[0])
print("NAME:", record[1])
print("DISEASE:", record[2])
N += 1
except:
f.close()
print('Total number of Covid-19 Patients =', N)

You might also like