This page contains the CBSE Computer Science with Python class 12 Unit-2 chapter 3 Data File Handling. You can find the solutions for chapter 3 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Data File Handling questions and answers for the Exercise.
Exercise
Question 1
1. Consider the following code:
file = open('textfile.txt','w')word = ''while word.upper() != 'END':word = raw_input('Enter a word use END to quit')file.write(word + '\n')file.close()
The above program creates a file storing a list of words. What is the name of file on hard disk containing list of words?
Answer 1
The file name created on disk is
textfile.txt.Question 2
2. Human readable form of file is called .
Answer 2
Human readable form of file is called a text file (plain text file).
Question 3
3. Write a
try ... except statement that attempts to open a file for reading and catches the exception thrown when the file does not exist.Answer 3
try:
f = open("myfile.txt", "r")
f.close()
except IOError:
print "File does not exist."
Question 4
4. Compare and contrast
read(), readline() and readlines().Answer 4
Basis
read()readline()readlines()Return type
String
String
List of strings
Data read per call
Whole file (or given size)
Only one line
All lines together
Best use case
When entire content is needed at once
When reading one line at a time
When processing/storing lines as a list
Question 5
5. How is
write() different from writelines()?Answer 5
Basis
write()writelines()Input accepted
Takes one string at a time.
Takes an iterable/sequence of strings (list, tuple, etc.).
Amount written per call
Writes exactly that one string.
Writes all strings from the sequence in order.
Newline handling
No newline is added automatically.
No newline is added automatically; each string should include
\n if needed.Typical use
When writing single messages/lines step by step.
When writing multiple lines already stored in a list.
Question 6
6. In how many ways can end of file be detected?
Answer 6
End of file can be detected in two common ways:
1.
When
read() or readline() returns empty string "".2.
By checking file pointer position with file size using
tell() and seek().Question 7
7. How many file modes can be used with the
open() function to open a file? State the function of each mode.Answer 7
Mode
Purpose
Description
rRead
Opens existing text file for reading.
wWrite
Creates new text file or truncates existing file.
aAppend
Writes at end of text file.
r+Read/Write
Reads and writes an existing file.
w+Write/Read
Creates/truncates and allows read/write.
a+Append/Read
Appends and allows reading.
rb, wb, abBinary modes
Read/write/append binary files.
rb+, wb+, ab+Binary update modes
Read/write/append binary with update.
Question 8
8. What does the
seekg() and seekp() functions do?Answer 8
•
seekg() repositions the get pointer (reading position) in a file stream.•
seekp() repositions the put pointer (writing position) in a file stream.•
In Python, similar work is done by
seek() (move pointer) and tell() (get pointer position).Question 9
9. Explain the use of output functions
write() and writeline()writelines() with an example each.Answer 9
write() is used to write a single string to a file. It is useful when we want to write one line or one block of text at a time.# Example: write()
f = open("out1.txt", "w")
f.write("Welcome to file handling\n")
f.close()
writelines() is used to write multiple strings (from a list/tuple) to a file in one call. It does not add newline automatically, so \n should be included where needed.# Example: writelines()
g = open("out2.txt", "w")
g.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
g.close()
Note: In Python, the function name is
writelines().Question 10
10. Write a function that writes a structure to disk and then reads it back and displays it on screen.
Answer 10
import pickle
# Write a structured record to binary file, read it back, and display it
def write_read_structure():
# Example structure (dictionary)
student = {"roll": 101, "name": "Riya", "marks": [90, 88, 95]}
# Store structure in binary file
f = open("student.dat", "wb")
pickle.dump(student, f)
f.close()
# Read same structure back from file
f = open("student.dat", "rb")
data = pickle.load(f)
f.close()
print data
Question 11
11. Using the file mentioned in Question 1, write a function to read the file and display a numbered list of words.
Answer 11
# Read textfile.txt and print words with serial numbers
def display_numbered_words():
f = open("textfile.txt", "r")
i = 1
for line in f:
# strip removes newline before display
print i, ":", line.strip()
i = i + 1
f.close()
Question 12
12. In the code (given in Question 1), the word
END used to indicate end of word list is also stored in the file. Modify the code so that END is not stored in the file.Answer 12
# Take words from user and stop when END is entered
f = open("textfile.txt", "w")
while True:
word = raw_input("Enter a word (END to quit): ")
# Do not write END into the file
if word.upper() == "END":
break
f.write(word + "\n")
f.close()
Question 13
13. Write a function that takes three arguments: 1st input file, 2nd output file and 3rd transformation function. First argument is the file opened for reading, second argument is the file opened for writing and third argument is a function, which takes single string, performs a transformation of your choice and returns the transformed string. The function should read each line in the input file, pass the line through transformation function and then write transformed line to output file. One transformation can be: capitalize first alphabet of every word.
Answer 13
# Apply a transformation function to each input line
def process_file(fin, fout, transform):
for line in fin:
fout.write(transform(line))
# Sample transformation: capitalize each word
def capitalize_words(s):
return s.title()
# Open files and process line by line
infile = open("input.txt", "r")
outfile = open("output.txt", "w")
process_file(infile, outfile, capitalize_words)
infile.close()
outfile.close()
Content of
input.txt (example)python is fun
file handling is important
cbse class twelve
Content of
output.txt after transformation (example)Python Is Fun
File Handling Is Important
Cbse Class Twelve
Question 14
14. Write a function to create a text file containing following data:
Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don’t fing. Overlook and oversee are opposites. A house can burn up as it burns down. An alarm goes off by going on.
i)
Read back the entire file content using
read() or readlines() and display on screen.ii)
Append more text of your choice in the file and display the content of file with line numbers prefixed to line.
iii)
Display last line of file.
iv)
Display first line from 10th character onwards.
v)
Read and display a line from the file. Ask user to provide the line number to be read.
Answer 14
# Perform all file operations asked in Q14
def q14_solution():
f = open("funny.txt", "w")
# Write each sentence on a separate line
f.write("Neither apple nor pine are in pineapple.\n")
f.write("Boxing rings are square.\n")
f.write("Writers write, but fingers don't fing.\n")
f.write("Overlook and oversee are opposites.\n")
f.write("A house can burn up as it burns down.\n")
f.write("An alarm goes off by going on.\n")
f.close()
# (i)
f = open("funny.txt", "r")
print f.read()
f.close()
# (ii)
f = open("funny.txt", "a")
f.write("Practice makes a person better.\n")
f.close()
f = open("funny.txt", "r")
lines = f.readlines()
f.close()
i = 1
for line in lines:
print i, ":", line.rstrip()
i = i + 1
# (iii)
print "Last line:", lines[-1].rstrip()
# (iv)
print "First line from 10th character:", lines[0][9:].rstrip()
# (v)
ln = int(raw_input("Enter line number: "))
if ln >= 1 and ln <= len(lines):
print lines[ln - 1].rstrip()
else:
print "Invalid line number"
Question 15
15. Create a dictionary having decimal equivalent of Roman numerals. Store it in a binary file. Write a function to convert Roman number to decimal equivalent using the binary file data.
Answer 15
import pickle
# Store Roman numeral dictionary in a binary file
def create_roman_dict_file():
roman = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Open file in binary write mode and store dictionary
f = open("roman.dat", "wb")
pickle.dump(roman, f)
f.close()
# Convert Roman string to decimal using binary-file dictionary
def roman_to_decimal(num):
# Load dictionary back from binary file
f = open("roman.dat", "rb")
d = pickle.load(f)
f.close()
total = 0
i = 0
while i < len(num):
# Get current symbol value
val = d[num[i]]
if i + 1 < len(num) and val < d[num[i + 1]]:
# Subtractive case like IV, IX, XL, etc.
total = total + (d[num[i + 1]] - val)
i = i + 2
else:
total = total + val
i = i + 1
return total
Sample content stored in
roman.dat (logical dictionary before pickling){'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
Sample conversion
roman_to_decimal("MCMIV") -> 1904
Question 16
16. Write a program to delete the content provided by user from a binary file. The file is very large and cannot fit in computer’s memory.
Answer 16
# Stream through binary file and copy only required records
import pickle
import os
def delete_content(fname, target):
# Read original file and write filtered records to temp file
fin = open(fname, "rb")
fout = open("temp.dat", "wb")
try:
while True:
# Read one record at a time (memory efficient)
rec = pickle.load(fin)
# Skip only the target record
if rec != target:
pickle.dump(rec, fout)
except EOFError:
# End of file reached
pass
# Replace original file with updated temp file
fin.close()
fout.close()
os.remove(fname)
os.rename("temp.dat", fname)
Sample binary file records before deletion (logical view)
[10, 25, 30, 25, 40]
If
target = 25, file records after deletion (logical view)[10, 30, 40]
Question 17
17. Write a function to insert a sentence in a text file, assuming that text file is very big and cannot fit in computer’s memory.
Answer 17
import os
# Insert a sentence at a specific line using a temporary file
def insert_sentence_in_file(fname, sentence, line_no):
# Open original for read and temp for write
fin = open(fname, "r")
fout = open("temp.txt", "w")
i = 1
inserted = False
for line in fin:
# Insert sentence before requested line number
if i == line_no:
fout.write(sentence + "\n")
inserted = True
fout.write(line)
i = i + 1
if not inserted:
# If line_no is beyond file length, append at end
fout.write(sentence + "\n")
fin.close()
fout.close()
# Replace original file with modified file
os.remove(fname)
os.rename("temp.txt", fname)
Sample content of
notes.txt before insertionLine 1: Python
Line 2: File Handling
Line 3: Binary File
Sample content of
notes.txt after insert_sentence_in_file("notes.txt", "Inserted Line", 2)Line 1: Python
Inserted Line
Line 2: File Handling
Line 3: Binary File
Question 18
18. Write a program to read a file
Story.txt and create another file storing an index of Story.txt telling in which line each word appears. If a word appears more than once, then index should show all line numbers containing the word.
Hint: Dictionary with key as word(s) can be used to solve this.
Answer 18
# Build word index: word -> list of line numbers
def build_index(infile, outfile):
# Dictionary to store word occurrences
index = {}
f = open(infile, "r")
line_no = 1
for line in f:
# Normalize and split into words
words = line.lower().replace(",", " ").replace(".", " ").split()
for w in words:
# Add first occurrence or append new line number
if w not in index:
index[w] = [line_no]
elif index[w][-1] != line_no:
index[w].append(line_no)
line_no = line_no + 1
f.close()
# Write index in sorted word order
out = open(outfile, "w")
for word in sorted(index):
out.write(word + " : " + str(index[word]) + "\n")
out.close()
Sample content of
Story.txtPython is powerful.
Python is easy to learn.
Files are useful in Python.
Sample content of generated
index.txtare : [3]
easy : [2]
files : [3]
in : [3]
is : [1, 2]
learn : [2]
powerful : [1]
python : [1, 2, 3]
to : [2]
useful : [3]
Question 19
19. Write a function called
replace_file() that takes pattern string, replacement string and two file names as arguments. The function should read the first file and write the content into second file (creating it if necessary). If the pattern string appears anywhere in first file, it should be replaced by replacement string in second file.Answer 19
# Copy file1 to file2 while replacing pattern with replacement
def replace_file(pattern, replacement, file1, file2):
# Open source and destination files
f1 = open(file1, "r")
f2 = open(file2, "w")
for line in f1:
# Replace all occurrences in each line
f2.write(line.replace(pattern, replacement))
f1.close()
f2.close()
Sample content of source file
file1.txtPython is simple.
I like Python file handling.
Sample content of destination file
file2.txt after replacing Python with CBSE PythonCBSE Python is simple.
I like CBSE Python file handling.
Question 20
20. Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character
#.Answer 20
# Print only those lines that contain '#'
fname = raw_input("Enter filename: ")
# Open file in read mode
f = open(fname, "r")
for line in f:
if "#" in line:
print line.rstrip()
f.close()
Sample content of input file
sample.pyprint "Hello"
# This is a comment
x = 10 # inline comment
print x
Sample displayed output
# This is a comment
x = 10 # inline comment
Question 21
21. Reading a file line by line from beginning is a common task. What if you want to read a file backward? This happens when you need to read log files. Write a program to read and display content of a file from end to beginning.
Answer 21
# Read file lines and display them in reverse order
fname = raw_input("Enter filename: ")
# Read all lines first
f = open(fname, "r")
lines = f.readlines()
f.close()
# Print from last line to first line
for i in range(len(lines) - 1, -1, -1):
print lines[i].rstrip()
Sample content of input file
log.txtStart program
Read data
Write report
Program end
Sample displayed output (reverse order)
Program end
Write report
Read data
Start program
Question 22
22. Create a class
item to store information of different items existing in a shop. At least following is to be stored with respect to each item: code, name, price, qty. Write a program to accept the data from user and store it permanently in the file. Also provide user with facility of searching and updating the data in file based on code of item.Answer 22
import pickle
import os
# Class to store item details
class Item(object):
def __init__(self, code, name, price, qty):
self.code = code
self.name = name
self.price = price
self.qty = qty
# Add multiple item records to binary file
def add_items(fname):
# Open file in append-binary mode to keep old records
f = open(fname, "ab")
n = int(raw_input("How many items? "))
for i in range(n):
c = raw_input("Code: ")
nm = raw_input("Name: ")
p = float(raw_input("Price: "))
q = int(raw_input("Qty: "))
pickle.dump(Item(c, nm, p, q), f)
f.close()
# Search an item by code and display details
def search_item(fname, code):
# Read records one-by-one till match or EOF
f = open(fname, "rb")
found = False
try:
while True:
rec = pickle.load(f)
if rec.code == code:
print rec.code, rec.name, rec.price, rec.qty
found = True
break
except EOFError:
# No more records
pass
f.close()
if not found:
print "Item not found"
# Update quantity of an item using temporary file technique
def update_item_qty(fname, code, new_qty):
# Copy all records to temp; modify matching record
fin = open(fname, "rb")
fout = open("temp_item.dat", "wb")
try:
while True:
rec = pickle.load(fin)
if rec.code == code:
rec.qty = new_qty
pickle.dump(rec, fout)
except EOFError:
# End of records
pass
# Replace old file with updated file
fin.close()
fout.close()
os.remove(fname)
os.rename("temp_item.dat", fname)
Sample records in
item.dat after adding items (logical view)[('I101', 'Pen', 12.5, 50),
('I102', 'Notebook', 45.0, 30),
('I103', 'Pencil', 5.0, 80)]
Sample search result for code
I102I102 Notebook 45.0 30
Sample records after
update_item_qty("item.dat", "I102", 45) (logical view)[('I101', 'Pen', 12.5, 50),
('I102', 'Notebook', 45.0, 45),
('I103', 'Pencil', 5.0, 80)]