File Handling || Important Questions || Class 12 || Sumita-Arora || Preeti-Arora || Computer Science
Q. What are the different file-processing modes supported by Python?
Q. What is the difference between readline() and readlines() function?
Q. What is the difference between "w" and "a" modes?
Q. Differentiate between file modes r+ and w+ with respect to python.
Q. Differentiate between file modes r+ and rb+ with respect to Python.
Q. 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()
Q. What are the advantages of saving data in:
(i) Binary form
(ii) Text form
Q. What is a CSV file?
Q. What are the advantages of CSV file formats?
Q. Differentiate between a text file and a binary file.
Q. Write a method in Python to read lines from a text file MYNOTES.TXT and display those lines which start with the alphabet 'K'.
Q. What are the advantages of saving data in:
(i) Binary form
(ii) Text form
Q. Write a function file_long() that accepts a filename and reports the file's longest line.
Q. Write a program to count the number of uppercase alphabets present in a text file "Pome.txt".
Q. 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.
Q. Write a program that reads characters from the keyboard one by one. All lower case characters get stored inside the file LOWER, all upper case characters get stored inside the file UPPER and all other characters get stored inside file OTHERS.
Q. Reading a file line by line from the beginning 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 file from end to beginning.
Q. 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
Q. Write a method in Python to write multiple lines of text contents into a text file daynote.txt line.
Q. Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.
Q. Write a user-defined function in Python that displays the number of lines starting with 'H' in the file Para.
txt. Example, if the file contains:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
Then the line count should be 2.
Q. Consider a binary file Employee.dat containing details such as empno: ename: salary (separator ':'). Write a Python function to display details of those employees who are earning between 20000 and 40000 (both values inclusive).
Q. Write a function countmy() in Python to read the text file "DATA.TXT" and count the number of times "my" occurs in the file.
For example, if the file "DATA.TXT" contains "This is my website. I have displayed my preferences in the CHOICE section." - the countmy() function should display the output as: "my occurs 2 times".
Q. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 4 characters.
Q. Write a method in Python to read lines from a text file DIARY.TXT and display those lines which start with the alphabet 'P'.
Q. Consider the file “SarojiniPoem.txt”
Autumn Song
Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.
Hark to a voice that is calling
To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have gone,
And why should I stay behind?
Sarojini Naidu
Based on the above file, answer the following question:
(a) What would be the output of following code?
file = open ("sarojiniPoem.txt","r")
text = file.readlines()
file.close()
for line in text :
print (line , end = ' ' )
print ( )
(b) Modify the program so that the lines are printed in reverse order.
(c) Modify the code so as to output to another file instead of the screen. Let your script overwrite the output file.
(d)Change the script of part (c) that it append output to an existing file.
(e) Modify the program so that each line is printed with a line number at beginning.
Q. Write a program using Dictionary and Text files to store roman numbers and find their equivalents.
Q. Observe the following code and answer the questions that follow:
File = open ("Mydata","a")
_______#Blank1
File.close()
(i) What type (Text/Binary) of file is Mydata?
(ii) Fill the Blank1 with statement to write "ABC" in the file "Mydata"
Q. How many file objects would you need to manage the following situations:
(a) To process four files sequentially.
(b) To merge two sorted files into third file.
Q. Write a program that reads a text file and then create a new file where each character‘s case is inverted.
Q. Write code to print just the last line of a text file 'data.txt'.
Q. Create a file phonebook.det that stores the details in following format:
Name Phone
Jiving 8666000
Kriti 1010101
:
Obtain the details from the user.
Q. Write a program to edit the phone number of “Arvind” infile “phonebook.det”. If there is no record for “Arvind”, report error.
Q. Write a function in Python to count the number of lines in a text file 'STORY.TXT' which are starting with the alphabet 'A'.
Q. 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.
Q. Write a function in python to count the number of lines in a text file 'STORY.TXT' which is starting with an alphabet 'A'.
Q. Following is the structure of each record in a data file named "PRODUCT.DAT".
("prod_code": value, "prod_desc": value, "stock": value)
The values for prod_code and prod_desc are strings and the value for stock is an integer.
Write a function in Python to update the file with a new value of stock. The stock and the product_code, whose stock is to be updated, are to be inputted during the execution of the function.
Q. 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.
Q. What is the difference between read() and readlines() function?
Q. Differentiate between the following:
(i) f = open('diary.txt', 'r')
(ii) f = open('diary.txt', 'w')
Q. Write a single loop to display all the contents of a text file poem.txt after removing leading and trailing white-spaces.
Q. Write a function stats() that accepts a filename and reports the file's longest line.
Q. What is the output of following code fragment? Explain.
out = open("output.txt", "w")
out.write("Hello, world! \n")
out.write("How are you?")
out.close()
print (open("output.txt").read())
Q. Write a function remove_lowercase() that accepts two filenames, and copies all lines that do not start with a lowercase letter from the first file into the second.
Q. What is the output of following code ?
file ("e:\\poem.txt", "r").readline().split()
Recall that poem.txt has some leading and trailing whitespaces.
Q. What is the output of following code ?
file("e: \\poem.txt", "r").readline()
Q. What is the output of following code ?
fh = file ("poem.txt", "r")
size = len(fh.read())
print (fh.read (5))
Q. Write a program to display all the records in a file along with line / record number.
Q. What is the output produced by following code ?
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()
Q. The file "New.txt" contains the following:-
Better than Heaven or Arcadia
I love thee, O my India !
And thy love I shall give
To every brother nation that lives.
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()
Q. Two identical files (p1.txt and p2.txt) were created by following two codes (carefully go through the two codes given below).
(a)
obj = open("p1.txt", "w")
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()
(b)
obj = open("p2.txt","w")
obj.write("Better than Heaven or Arcadia \n")
obj.write("I love thee, O my India!\n")
obj.write("And thy love I shall give\n")
obj.write("To every brother nation that lives.\n")
obj.close()
What would be the output produced if the files are read and printed with following code.
Q. Considering the two files pl.txt and p2.txt created in previous question, what output will be produced by following code fragments ?
(a)
obj1 = open("p1.txt", "r")
s1 = obj1.readline()
s2= obj1.read(15)
print (s2)
obj1.close()
(b)
obj1 = open("p2.txt", "r")
s1 = obj1.readline()
s2 = obj1.read(15)
print(s2)
obj1.close()
Q. Consider the file p2.txt created above. Now predict the output of following code that works with p2.txt. Explain the reason behind this output.
fp1= open("p2.txt", "r")
print (fp1.readline(20))
s1= fp1.readline (30)
print(s1)
print (fp1.readline (25))
Q. Read the code given below and answer the question:-
fh = open("main.txt", "W")
fh.write("Bye")
fh.close()
If the file contains “GOOD” before execution, what will be the contents of the file after execution of this code?
Q. A given text file "data.txt" contains:
Line 1\n
\n
Line 3
Line 4
\n
Line 6
What would be the output of following code?
fh = open ("data.txt", "r")
1st = fh.readlines()
print (1st[0], end = '')
print (1st[2], end = "")
print (1st[5], end = '')
print (1st[1], end = '')
print (1st[4], end = '')
print (1st[3])
Q. Write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting with a "@" sign.
Q. Consider the following statement. In which file mode is the file opened ? Justify your answer.
with open( 'poen.txt') as f:
Q. What is pickling process? What is its need ?
Q. What is unpickling?
Q. What is the difference between a regular text file and a delimited text file ?
Q. What is the significance of newline = ’’ argument in file open() function?
Q. What does csv.writer object do?
Q. What is the function of csv.reader object?
Q. What will be stored in the file school.csv after the following code is executed?
data = [[ 'DRS Delhi', 'Esha', 'Badminton'], ['BTS Patna', 'Abhi', 'Tennis']]
import csv
with open('schoo;.csv', 'w', newline ="") as csvfile:
writer = csv.writer(csvfile, delimiter = ',')
writer.writerow(['School', 'Nickname', 'Sport'])
writer.writerows(data)
Q. Write a program to remove all the lines that contain the character 'a' in this file and write other lines into another file.
Q. Differentiate between the following:-
(i) f = open ('diary.txt', 'r')
(ii) f = open ('diary.txt", "w')
Q. 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)
Q. Following code is written to update a record in a file opened with following code:
import pickle
fin = open("Stu.dat', 'rb')
try:
while True:
_____ = fin.tell() # Line 1: store file-pointer position before reading the record
stu = pickle.load(fin))
if stu['Marks'] in [92, 93, 94]:
stu[ 'Marks'] += 3 #changes made in the record
fin._____ (_____) # Line 2 :place the file-pointer at the exact location of the record
pickle.dump(stu, fin) # now write the updated record on the exact location
except:
:
Fill in the blanks in Lines 1 and 2 to complete the code.
Q. Identify the error in the following code:
1. import pickle
2. data = ['one', 2, [3, 4, 5]]
3. with open('data2.dat', 'rb') as f:
4. pickle.dump(data, f)
Q. Identify the error in the following code.
1. f = open("/tmp/workfile', 'r+')
2. f.write('0123456789abcdef')
3. f.write('xyz8466')
4. f.close()
5. f.seek (0)
6. f.read()
Q. 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)
Q. Write a program to read a text file and display the count of lowercase and uppercase letters in the file.
Q. Your recipe uses some ingredients. Write a program to store the list of ingredients in a binary file.
Q. Write a method in python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word "India".
For example:- If the content of the file is
"India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is
capable of reaching."
The output should be 4
Q. Write a method in python to read lines from a text file MYNOTES.TXT, and display those lines, which are starting with an alphabet "K".
Q. Considering the following definition of dictionary MULTIPLEX, write a method in python to search and display all the content in a pickled file CINEMA.DAT, where MTYPE key of the dictionary is matching with the value "Comedy".
MULTIPLEX = {'MNO': _____, 'MNAME": _____, 'MTYPE': _____}
Q. Write a program to increase the salary by Rs. 2000/- of the employee having empno as 1251 in the file empl.dat.
Q. Take a sample text file and find the most commonly occurring word. Also, list the frequencies of words in the text file.
Q. Write a program to read following details of sports' performance (sport, competitions, prizes-won) of your school and store into a csv file delimited with tab character.
Q. 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.
Thankyou sir this was so helpful
ReplyDeleteWelcome : )
DeleteTHANK YOU VERY MUCH : ))
ReplyDeleteWelcome : )
Deleteomg tysm it's so hard to find the solutions
ReplyDeletethx a LOT
Welcome : )
DeleteSir i will do only can achieve 70 marks
ReplyDeleteYes.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )