Class-12 File Handling Question and Answer
Class-12 File Handling Question and Answer
FILE HANDLING
EXAM BASED QUESTION
1.Differentiate between file modes r+ and w+ with respect to python.
Answer =
• r+ opens a file for both reading and writing. The file pointer placed at the beginning of the
file.
• w+ opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
2. What is the difference between readline() and readlines() function?
Answer =
The readline() function reads from a file in read mode and returns the next line in the file or a
blank string if there are no more lines. (The returned data is of string type.)
The readlines() function also reads from a file in read mode and returns a list of all lines in
the file. (The returned data is of list type.)
3.What is the difference between "w" and "a" modes?
Answer =
"w" mode :- If file exists, python will delete all data of the file.
"a" mode :- If file exists, the data in the file is retained and new data being written will be
appended to end.
4.Differentiate between file modes r+ and w+ with respect to python.
Answer =
• r+ opens a file for both reading and writing. The file pointer placed at the beginning of the
file.
w+ opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
5.Differentiate between file modes r+ and rb+ with respect to Python.
Answer =
r+ opens a file for both reading and writing. The file pointer is placed at the beginning of the
file.
rb+ opens a file for both reading and writing in binary format. The file pointer is placed at the
beginning
of the file.
6.What would be the data type of variable data in the following statements?
(a) data = f.read()
(b) data = f.read(10)
(c) data = f.readline()
(d) data = f.readlines()
Answer =
Answer =
(i)
• It is faster and use less memory.
• Computer can easily understand this form.
• We Can Store Any type of Data in it.
8.HomeData File Handling (Preeti Arora)
What is a CSV file?
0 Comments
8. What is a CSV file?
Answer =
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a
spreadsheet or Database. A CSV file stores tabular data (number and text) in plain text.
In other words :-
CSV files are Comma Separated Values files. These are the delimited files when mostly
comma (delimiter character which separates the values) is used to separate the values
stored. The CSV files can also a delimiter other than comma but comma is the default
delimiter.
Answer =
A text file stores data as ASCII/UNICODE characters whereas a binary file stores data in
binary format (as it is stored in memory). Internal conversion is required in text file and,
hence, it is slower but binary file does not need any translation and so is faster.
10.Write a method in Python to read lines from a text file MYNOTES.TXT and display those
lines which start with the alphabet 'K'.
Answer :
def display () :
file = open ('MYNOTES.TXT', 'r')
line = file.readline()
while line :
if line [ 0 ] == 'K' :
print (line)
line = file.readline ()
file.close()
display()
This is PathWalla
So, Here you will get Solutions
Korea is a good country
This is due to
Korean people are very good.
So, Our Output :
Answer =
(i)
• It is faster and use less memory.
• Computer can easily understand this form.
• We Can Store Any type of Data in it.
(ii)
• It can easily understand by human.
• It can excess easily.
12. Write a function file_long() that accepts a filename and reports the file's longest line.
Answer =
Answer =
count = 0
file.close()
14.Write a function remove_lowercase() that accepts two file names, and copies all lines that
do not start with a lowercase letter from the first file to the second file.
Answer =
f1 = open("pathwala.txt",'r')
data = f1.readlines()
content = ""
for i in data :
content += i+"\n"
f1.close()
16.Write a statement in Python to perform the following operations:
• To open a text file "MYPET.TXT" in write mode
• To open a text file "MYPET.TXT" in read mode
Answer =
Answer =
def write () :
f = open ("daynote.txt", 'w')
while True:
line = input ("Enter line:")
f.write (line)
choice = input("Are there more lines (Y/N):")
if choice == 'N':
break
f.close()
18.Write a Python program to display the size of a file after removing EOL characters,
leading and trailing white spaces and blank lines.
Answer =
f1 = open("path.txt",'r')
data = f1.readlines()
content = ""
for i in data :
for j in i :
if j.isalnum():
content += j
print("file size:-",len(content),"bits")
f1.close()
19. Write a user-defined function in Python that displays the number of lines starting with 'H'
in the file Para.
Answer =
Answer =
import pickle
numerals = {1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
500:'D',900: 'CM', 1000:'M'}
22. Write a program using Dictionary and Text files to store roman numbers and find their
equivalents.
Answer =
import pickle
numerals = {1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
500:'D',900: 'CM', 1000:'M'}
Output :-
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: 9
Equivalent roman number of this numeral is: IX
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: 4
Equivalent roman number of this numeral is: IV
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: 50
Equivalent roman number of this numeral is: L
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: 100
Equivalent roman number of this numeral is: C
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: 1000
Equivalent roman number of this numeral is: M
Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000:
or enter -1 to exit
Enter number: -1
Thank You
23.Observe the following code and answer the questions that follow:
Answer =
25.Write a program that reads a text file and then create a new file where each character‘s
case is inverted.
Answer =
f1 = open("path.txt","r")
f2 = open("wala.txt","w")
data = f1.readlines()
for i in data :
for j in i :
if j.isupper() :
f2.write(j.lower())
elif j.islower() :
f2.write(j.upper())
else :
f2.write(j)
f1.close()
f2.close()
Path.txt contain :-
This is Pathwalla Website
Output :-
Walla.txt contain :-
Answer =
Name Phone
Jiving 8666000
Kriti 1010101
:
Answer =
f = open("phonebook.det ","w")
f.write("Name \t")
f.write("Phone \t")
f.write("\n")
while True :
name = input("Enter name :-")
phone = input("Enter Phone :-")
f.write(name +"\t")
f.write( phone + "\t")
f.write("\n")
user = input("Enter quit or continue (Q/C) :-")
if user == "Q" or user == "q":
break
f.close()
print("Thankyou")
28.Write a program to edit the phone number of “Arvind” infile “phonebook.det”. If there is no
record for “Arvind”, report error.
Answer =
Try = 0
f = open("phonebook.det","r")
data = f.readlines()
f.close()
f = open("phonebook.det","w")
name = input("Enter name which you want search :-")
for i in range(len(data)) :
line = data[ i ] . split()
if line[0] == name :
phone = input("Enter new Phone :-")
data[ i ] = name + " " + phone
Try = 1
if Try != 1 :
print("Try again !!!!! ")
for i in range(len(data)) :
line = data[ i ] . split()
for j in line :
f.write( j + "\t")
f.write("\n")
f.close()
print("Thankyou")
29.Write a function in Python to count the number of lines in a text file 'STORY.TXT' which
are starting with the alphabet 'A'.
Answer =
def COUNTLINES () :
file = open ('STORY.TXT', 'r')
lines = file.readlines ()
count=0
for w in lines :
if w[0] == "A" or w[0] == "a" :
count = count + 1
print ("Total lines : ", count)
file.close()
30.A text file contains alphanumeric text (say an.txt). Write a program that reads this text file
and prints only the numbers or digits from the file.
Answer =
F = open("an.txt", "r")
for line in F :
words = line.split()
for i in words :
for letter in i :
if(letter. isdigit()) :
print(letter)
31.Write a function in python to count the number of lines in a text file 'STORY.TXT' which is
starting with an alphabet 'A'.
Answer =
def COUNTLINES():
file = open('STORY.TXT', 'r')
lines = file.readlines()
count = 0
for w in lines :
if w [0] == "A" or w[0] == "a" :
count = count + 1
print("Total lines started with 'A' or 'a'", count)
file.close()
32. Create a CSV file "Groceries" to store information of different items existing in a shop.
The information is to be stored w.r.t. each item code, name, price, qty. Write a program to
accept the data from user and store it permanently in CSV file.
Answer =
import csv
data = []
while True :
item_code = input("Enter item code :-")
name = input("Enter name :-")
price = input("Enter price :-")
qty = input("Enter Quantity :-")
data += [[ item_code, name, price, qty ]]
user = input("Do you want to enter more data (yes/no)")
if user == "No" or user == "no" :
break
with open("Groceries.csv","w",newline="") as f :
csv_w = csv.writer(f,delimiter=',')
csv_w.writerows(data)
33.Differentiate between the following:
(i) File has been opened in read mode with file handle f.
(ii) File has been opened in write mode with file handle f.
34.Write a single loop to display all the contents of a text file poem.txt after removing leading
and trailing white-spaces.
Answer :-
Answer :-
out.close()
print (open("output.txt").read())
Answer :-
Hello, world!
How are you?’
Explanation
The first line of the code is opening the file in write mode; the next two lines write text to the
file. The last line opens the file and from that reference reads the file-content. Function file()
does the same as that of open(). Thus file("output.txt") will give the reference to open file, on
which read() is applied.
37.What is the output of following code ?
Answer :-
[WHY?']
38.What is the output of the following code ?
Answer :-
No output
Explanation:- The fh.read() of line 2 will read the entire file content and place the file pointer
at the end of file. For the fh.read (5), it will return nothing as there are no bytes to be read
from EOF thus print() statement prints nothing.
39.Write a program to display all the records in a file along with line / record number.
Answer :-
fh = open("Result.det", "r")
count = 0
rec = ""
while True :
rec = fh.readline()
if rec == "":
break
count = count + 1
obj = open("New.txt","w")
obj.write("A poem by Paramhansa Yogananda ")
obj.write("Better than Heaven or Arcadia")
obj.write("I love thee, O my India!")
obj.write("And thy love I shall give")
obj.write("To every brother nation that lives.")
obj.close()
obj1 = open("New.txt","r")
s1 = obj1.read(48)
print(s1)
obj1.close()
Answer :-
Considering the given file, what output will be produced by the following code ?
obj1 = open("New.txt","r")
s1 = obj1.readline()
s2 = obj1.readline()
s3 = obj1.readline()
s4 = obj1.read(15)
print (s4)
obj1.close()
Answer :-
To every brothe
Explanation :-
Due to "s1 = obj1.readline()" statement, the pointer goes to the second line, and again due to
"s2 = obj1.readline()" and "s2 = obj1.readline()" the pointer goes to 4th line then "s4 =
obj1.read(15)" statement read 15 character of that txt file. So our output will be :- To every
brothe.
42.Write a program that copies a text file "source.txt" onto "target.txt" barring the lines
starting with a "@" sign.
Answer :-
>>>filter("source.txt", "target.txt")
43.What is pickling process? What is its need ?
Answer :-
Objects have a specific structure which must be maintained while storing or accessing them.
Python provides a special module - the pickle module to take care of that. The pickling
process serializes the objects and converts them into byte stream so that they can be stored
in binary files.
44.What is the difference between a regular text file and a delimited text file ?
Answer :-
Regular Text files are the files which store the text in the same form as typed (ASCII or
Unicode). Here the newline character ends a line and the text translations take place. These
files have a file extension as .txt.
45.Delimited Text files are also text files where a specific character is stored to separate the
values, i... after each value, e.g., a tab or a comma after every value, .g., TSV files (Tab
Separated Values files) or CSV files (Comma Separated Values files).
46.What is the significance of newline = ’’ argument in file open() function?
Answer :-
When newline = " ensures that no end of line (EOL) translation would take place while
storing the file contents on the disk. By default text files are stored with some text
translations, EOL translation is one of these. By specifying newline = " as argument to file
open() function, we ensure that no EOL translation takes place. This is useful when we use
the files on different platforms.
47.What does csv.writer object do?
Answer :-
The csv.writer object adds delimitation to the user data prior to storing data in the csv file on
storage disk.
48.Write a program to remove all the lines that contain the character 'a' in this file and write
other lines into another file.
Answer :-
myfile.close()
newfile.close()
print("Newly created file contains")
print("------------")
newfile = open("nswer.txt","r")
line = ""
while line:
line = newfile.readline()
print(line)
newfile.close()
The output produced by above program is:-
Answer :-
(i) The text file diary.txt is opened in read mode.
(ii)The text file diary.txt is opened in write mode.
50.What will be displayed by the following code ?
import pickle
Names = ["First", "second", 'third', 'fourth', 'Fifth']
lst = []
for i in range(-1, -5, -1):
lst.append(Names[i])
with open("test.dat", 'wb') as fout:
pickle.dump(lst, fout)
with open("test.dat", 'rb') as fin:
nlist = pickle.load(fin)
print(nlist)
Answer :-
1. import pickle
2. data = ['one', 2, [3, 4, 5]]
3. with open('data2.dat', 'rb') as f:
4. pickle.dump(data, f)
Answer :-
The file is opened in read mode and dump() function tries to write onto file, hence the error.
1. f = open("/tmp/workfile', 'r+')
2. f.write('0123456789abcdef')
3. f.write('xyz8466')
4. f.close()
5. f.seek (0)
6. f.read()
Answer :-The lines 5 and 6 will raise the error as no operation can take place in a closed
file-file is closed at line4. Since the file is opened in read as well write mode, we just need to
bring line 4 at the end of the code.
53.Identify the error in the following code?
1. import csv
2. line [[1,2,3], [4, 5, 6]]
3. with open (path, "w", newline = '') as csv_file:
4. writer csv.writer(csv_file, delimiter = '|')
5. for line in data:
6. writer.writerow (line)
Answer :-
writer.writerows (line)
54.Write a program to get item details (code, description and price) for multiple items from
the user and create a csv file by writing all the item details in one go.
Answer :-
import csv
fh = open("Items.csv", "w")
iwriter = csv.writer (fh)
ans = 'y'
itemrec = [['Item_Name', 'Description"', 'Price']]
print("Enter item details ")
while ans == 'y' :
iname = input("Enter Item code : ")
desc = input("Enter description : ")
price = float(input("Enter price: "))
itemrec.append([iname, desc, price])
ans = input ("Want to enter more items? (y/n)... ")
else:
iwriter.writerows(itemrec)
print("Records written successfully.")
fh.close()
Enter item details
Enter Item code : 0012
Enter description : PEN
Enter price: 7.5
Want to enter more items? (y/n)... y
Enter Item code : 2514
Enter description : PENCIL
Enter price: 4
Want to enter more items? (y/n)... y
Enter Item code : 3678
Enter description : COPY
Enter price: 40
Want to enter more items? (y/n)... n
Records written successfully.
>>>
The file contain data like :-
Item_Name,"Description""",Price
0012,PEN,7.5
2514,PENCIL,4.0
3678,COPY,40.0