File Handling in Python Computer Science Class 12

File handling in Python assignment solutions for Class 12 Computer Science. Solved Short and Conceptual Questions and assignment from Sumita Arora Computer Science (Python) Book for the students of CBSE and other board following NCERT syllabus. Very useful for CBSE Class XII Board Exams Question Paper.

Short Answer/ Conceptual Question

Q.1 What is the difference between “w” and “a” modes ?

Answer:
“w” means write mode, in this mode of the file is first fully deleted and then the file is to be written. In appending mode “a” nothing is deleted the file is added by the new content.

Q.2.What is the significance of file-object ?

Answer:
A file object is used to be reference of file on disk and open it for a number of tasks.
f=open(“file_path”,’r’) #Here, f is file object.

Q.3.How is the file open() function different from close() function?

Answer:
The open() function is used in to open the file and create file object. The close() function is used to break the link of file objects and file on the disk.
f=open(“file_path”,’r’)
f.close()

Q.4.Write statements to open a binary file C:\Myfiles\Text1.txt in read and write mode by specifying the file path in two different formats.

Answer:
Double slash
f=open(“ C:\\Myfiles\\Text1.txt “,’r+’)
Raw String
f=open( r” C:\Myfiles\Text1.txt “,’r+’)

Q.5.While a file is opened for output, what happens when
(i)The mentioned file does not exist
Answer
:
r mode- read mode shows an error
w mode- start a new file with the same name as open file given
a mode- start a new file with the same name as open file given
(ii)The mentioned file does exist.
r mode- shows the file for reading
w mode- delete the file contents and start writing file by user inputs
a mode- open the files with contents and write extra content which user inputs.

Q.6.What role is played by file operations? Describe the various file mode constants and their meanings.

Answer:
Mode governs how the file be used.
r-read mode , the file is read in read mode
w-write mode, the files delete existing content start from fresh with the same file name whether it exist or not
a-append mode, the file remains the same and contents can be added changed according to use.
r+-read and write- shows error if file doesnot exist
w+-write and read- new file is created if file not exist
a+-write and read-without truncated data

Q.7.What are the advantages of saving data in:
(i)Binary form
(ii)text form
Answer:

(i)Binary form stores in the same format as in memory .It tends to use less memory text format. The data is stored in raw format(binary ) and returned as it without translation. speed of access is faster.
(ii)Each file stored information in text file and is terminated with special character EOL.Text file are less prone to be corrupted.

Q.8.When do you think text files should be preferred over binary files?

Answer:
Text files should be preferred over binary files when the file has to be read by humans. Binary are hard to read by human.

Q.9. Write a statement in python to perform the following operations:
(a)To open a text file “BOOK.TXT”in read mode
(b)To open a text file “BOOK.TXT”in write mode

Answer:
(a)f=open(“BOOK.TXT” “,’r’)
(b) f=open(“BOOK.TXT” “,’w’)

Application Based Questions

Q.1. How are following codes different from one another?

Answer:
(a)my_file=open(‘poem.txt’,’r’)

my_file.read()
(b my_file=open(‘poem.txt’,’r’)

my_file.read(100)
Answer:

The (a) code read all of the file poem.txt whereas the (b) read the poem.txt file to 100 bytes.

Q.2. If the file ‘poemBTH.txt’ contains the following poem (by Paramhans Yoganand ) :
God made the Earth;

Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the World.
Hail, mother of religions, Lotus, scenic beauty and sages!

What outputs will be produced by both the code fragments given below :
i. What outputs will be produced by the code fragment given below :
my_file =open(‘poemBTH.txt’, ‘r’)
my_file.read()
ii. What outputs will be produced b y the code fragment given be low :
my_file = open(‘poemBTH.txt’, ‘r’)
my_file.read(100)

Answer:
The (i) code read all of the file poem.txt whereas the (ii) read the poem.txt file to 100 bytes.
output (i) –
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the World.
Hail, mother of religions, Lotus, scenic beauty and sages!

Output (ii)-
Man made confining countries
And their fancy-frozen boundaries.
But with unfound

Q.3.Consider the file poemBTH.txt given above. What output will be produced by following code fragment ?
obj1 = open(‘poemBTH.txt’, ‘r’)
s1 = obj1.readline()
s2.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()

Answer:
Error s2 is not defined.

Q.4. Consider the file “poemBTH.txt” and predict the outputs of the following code fragments if the file has been opened in filepointer file1 with code:
file1 = open (“E\\mydata\\poemBTH.txt”, ‘r+’)

(a)
print (“A. Output 1”)
print (file1.read())
print ()
Answer:
A. Output 1
God made the Earth;
Man made confusing countries.
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the world.
Hail, mother of religions, lotus, scenic beauty, and sages!

(b)
print (“B. Output 2”)
print (file1.readline())
print ()
Answer:
B.Output2

(c)
print (“C. Output 3”)
print (file1.read(9))
print ()
Answer:
C.Output 3

(d)
print (“D. Output 4”)
print (file1.readline(9) )
Answer:
D.Output4

(e)
print (“E. Output of Readlines function is”)
print (file1.readlines() )
print ()
Answer:
E. Output of Readlines function is
[]

Q.5.What is following code doing?
File= open(“contacts.csv”,”a”)
name= input(“please enter name”)
phno=input(“Please enter phone number”)
File.write(name+”,”+phno+”\n”)

Answer:
First it is opening “contacts.csv” in append mode then it is taking name, phone n.o as input, then the file is writen the name and phone n.o.

Q.7.Consider the file “contacts.csv” created in above question and figure out what the following code is trying to do?
name=input(“Enter name:”)
file=open(“contacts.csv”,”r”)
for line in file:
if name in line:
print(line)

Answer:
Will read the file line by line.

Q.8.Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is following code fragment doing?
f=open(“poemBTH.txt”,”r”)
n1=0
for line in f:
n1+=1
print(n1)

Answer:
program reads number of lines present in file “poem.txt”.

Q.9. If you use the code of Q.8 with p1.txt created in solved promblem 14, what would be its output?

Answer:
The p1.txt file contain just 1 line.so output will be :
1

Q.10.Write a method in python to read the content from a text file diary.txt line by line and display the same on screen.

Answer:
f= open(‘diary.txt’,’r’)
l=f.readlines()
for line in l:
print(line)

Q.11. Write a method in python to write multiple line of text contents into a text file mylife.txt.line.

Answer:
f= open(‘mylife.txt’,’w’)
f.write(‘Hello \n’)
f.write(‘this is archit \n’)
f.write(‘this is life\n’)

Programming Practice/Knowledge based Questions :
File Handling in Computer Science Python Class 12

Q.1.Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space.

Answer:
file1 = open("portal.txt","r") #opening portal.txt in read mode
file2 = open("Express.txt","w") #opening Express.txt in write mode
lst = file1.readlines()
#file is opened
#welcome to archit gulia programs
i=0
for i in lst :
    word = i.split()
    file2.write( " ".join(word) )
    file2.write("\n")
#print("testing",i)
print("Program has successfully run")
file2.close()
file1.close()

Q.2.Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is ” Atheletics “.

Answer:
def portal( ) : #function  intialization is started from the next line 
    file1 = open("sports.txt","r") # text file is opened 
    file2 = open("Atheletics.txt","w")
    i=0
    lst = file1.readlines()
    for i in lst :
        print(i [ : 9 ])
        if i [ : 9 ] == "atheletic" or i [ : 9 ] == "Atheletic" :
            file2.write(i)
    file1.close() 
    file2.close()
    #print(i)
portal()

Q.3. A file contains a list of telephone numbers in the following form:
Arvind 7258031
Sachin 7259197

The names contain only one word the names and telephone numbers are separated by white spaces Write program to read a file and display its contents in two columns. 

Answer:
file = open("portal.txt", "r") #portal txt is opened
lst = file.readlines() # file is read 
i=0
for i in lst :
    data = i.split()
    print( data[0] ,end = "\t" )
    print("|" , end = "\t")
    print ( data[1] )
#print(i)
file.close()

Q.4.Write a program to count the words “to” and “the” present in a text file “Poem.txt”.

Answer: 
to_no = 0
i=0
the_no = 0
file = open("poem.txt", "r") #poem text file is opened
lst = file.readlines() #lines are read by line by line
for i in lst :
    word = i.split()
        for j in word :
            if j == "to" :
                to_no += 1
            elif j == "the" or j == "The" :
                the_no += 1
#print ("test",0)
print("Number 'to' : " , to_no)
print("Number 'the' : " , the_no)
file.close()

Q.5. Write a program to count the number of upper- case alphabets present in a text file “Article.txt”.

Answer:
count = 0
i=0 #i is intialised to zero
file = open("csstudy.txt","r")# csstudy file is opened
sen = file.read()
for i in range ( len(sen) ) :
    if sen[ i ].isupper() :
        count += 1
#print("test",i)
print("Number of upper case alphabet : ", count)
file.close()

Q.6.Write a program that copies one file to another. Have the program read the file names from user ?

Answer:
file = input("Enter the name of file with its formate : ")
old = open( file , "r") #opening a file in read mode
new = open("New file.txt", "w")#opening a new file in write mode
i=0
data = old.read()
new.write( data )
#print("test",i)
print(" Program run successfully ")
old.close()
new.close()

Q.7.Write a program that appends the contents of one file to another. Have the program take the filenames from the user.

Answer:
file1 = input("Enter the name of file which you want to append : ")#entering the append file name
file2 = input("Enter the name of original file : ")#entering the original file name
i=0
old = open( file2 , "r" ) #file 2 opened in read mode
new = open( file1 , "a" )
data = old.read()
new.write( "\n" + data)
print("Program running fine")
#print(i)
old.close()
new.close()

Q.8.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.

Answer: 
upper = open("upper.txt","w")#opening upper text file
lower = open("lower.txt" , "w" ) #openeing lower text file
other = open ("other.txt" , "w") #opening other text file
i=0
while True :
    user = input("Enter a charracter (for exit enter quit ): ")
    if user == "quit" or user == "Quit" :
         break #breaking the loop and moving to the after loop statement
    elif user.isupper() :
        upper.write( user + " " )
    elif user.islower( ) :
        lower.write( user + " " )
    else :
        other.write( user + " " )
#print(i)
upper.close()
lower.close()
other.close()

Q.9.
Write a function in Python to count and display the number of lines starting with alphabet ‘A’ present in a text file ” LINES.TXT”. e.g., the file “LINES.TXT”  contains the following lines:

A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.

The function should display the output as 3
.

Answer:
count = 0 #count is intialized to zero
file = open("line.txt","r") #open line.txt file and read mode
#i=0
lst = file.readlines()
for i in lst :
    if i[ 0 ] == "A" :
        print(i)
        count += 1
print("So for number of sentences started with A : ",count)
#print(i)
file.close()

Thanks friends, for visiting site. I hope you like the assignment solutions of File handling Class 12 Computer Science (Python).

Computer Science Class 12 Assignment Solutions : All Chapters

Leave a Comment

Your email address will not be published.