Chapter-5-File Handling, Type A, B & C NOTES
Chapter-5-File Handling, Type A, B & C NOTES
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.
(OR)
5. Q. When a file is opened for output, what happens when
6. What role is played by file modes in file operations? Describe the various file mode constants and their
meanings.
8. When do you think text files should be preferred over binary files?
When people want to read the data of the file then text file easy to understand, binary file not easily understand by
human. At that time text files should be preferred over binary files.
10. Explain how many file objects would you need to create to manage the following situations:
Yes, CSV file is different from a text file because CSV file are Comma Separated Value files and these files take
the extension as .csv .While text files are the files which store the text in the same form as typed. These file have a
file extension as .txt .
Yes, CSV file is different from a binary file because CSV file are Comma Separated Value files and easily
readable or understand by humans. While binary files easily understandable by computers.
14. How do you change the delimiter of a csv file while writing into it?
Answer =
By typing these type of syntax :-
<name-of-writer-object> = csv.write (<file-handle>, [delimiter = <delimiter-character>])
15. When and why should you suppress the EOL translation in csv file handling?
If you create a csv file on one operating system and use it on another. The EOL of one operating system will not
be treated as EOL on another operating system. Also, if you have given a character, say '\r', in your text string (not
as EOL but as part of a text string) and if you try to open and read from this file on a Macintosh system, what
would happen? Mac OS will treat every '\r' as EOL - yes, including the one you gave as part of the text string.
So what is the solution? Well, the solution is pretty simple. Just suppress the EOL translation by specify third
argument of open() as newline = (null string - no space in quotes).
If you specify the newline argument while writing onto a csv file, it will create a csv file with no EOL translation
and you will be able to use csv file in normal way on any platform.
16. If you rename a text file's extension as .csv, will it become a csv file? Why/why not?
Yes, text will become a csv file. Because if data is separated by any delimiter then that file can be form csv file.
17. Differentiate between “w” and “r” file modes used in Python while opening a data file. Illustrate the
difference using suitable examples.
• Then what outputs will be posted by both the code fragments given in question 1.
Output by (a) of Question 1 is that it will print all data of 'poemBTH.txt' in another word, it will
print full poem.
Output
>>> 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!
3. Consider the file 'poemBTH.txt' given above (in previous question). 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:
4.Write code to open file created in previous question and print it in following form:
Name : <name> Phone :< phone number>
5. Consider the file 'poem.txt' and predict the output of 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 ()
(b)
print ("B. Output 2")
print (file1.readline())
print ()
(c)
print ("C. Output 3")
print (file1.read(9))
print ()
(d)
print ("D. Output 4")
print (file1.readline(9) )
(e)
print ("E. Output of Readlines function is")
print (file1.readlines() )
print ()
6. Q. What is following code doing?
file = open("contacts.csv", "a")
name = input("Please enter name.")
phno = input("Please enter phone number.")
file.write (name + "," + phone + "\n")
Answer = It will take data from user and write data in file ‘contacts.csv’
7. Consider the file "contacts.csv" created in above Q. 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)
Name (Data) input from user and give the output if name (data) present in "contacts.csv" file then give full details
of that name(data), Otherwise it do nothing.
8. Consider the file poem.txt and predict the output of following code fragment. What exactly is following
code fragment doing?
f = open ("poemBTH.txt", "r")
nl = 0
for line in f:
nl += 1
print (nl)
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.
11. Write a method in python to write multiple line of text content into a text file mylife.txt line.
import pickle
list1 = ['Roza',{'a':23,'b':True}, (1, 2, 3), [['dogs', 'cats'],None] ]
list2 = ['Rita',{'x':45,'y':False}, (9, 5, 3), [['insects', 'bees'], None] ]
with open('data.pkl', 'wb') as f:
f.write(list1)
print(list1)
Answer :-
It will give an error because we cannot write in a binary file by using write(), we have to use pickle.dump() .
So, the correct program is
Import pickle
list1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None] ]
list2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None] ]
with open('data.pkl', 'wb') as f:
pickle.dump(list1 , f )
print(list1)
Output : -
['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
14.What is the output of the following considering the file data.csv given on the right
File data.csv contains:
Identifier; First name; Last name
901242; Riya; Verma
207074; Laura; Grey
408129; Ali; Baig
934600; Manit; Kaur
507916; Jiva; Jain
import csv
with open('C:\data.csv','r+') as f:
data = csv.reader(f)
for row in data:
if 'the' in row:
print(row)
Answer =
It will not give any output, because data.csv did not contain “the” word.
Answer = Error in line 3 that is there is not parameter present in reader() function.
16. Identify the error in the following code.
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb':
pickle. dump(data)
Ans: Error in line 3 that is open () function should be close like (open()) and also there is not present file handle.
Error in Line 4 that is file handle is not present in dump() function.
TYPE – C –Programming Practice / Knowledge based Questions
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.
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.
print("Name\t|\tPhone no. ")
for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )
file.close()
4. Write a program to count the words "to" and "the" present in a text file "Poem.txt".
to_no = 0
the_no = 0
for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1
file.close()
5. Write a function AMCount() in Python, which should read each character of a text file STORY.TXT,
should count and display the occurrence of alphabets A and M (including small cases a and m too).
Example: If the file content is as follows:
Updated information
As simplified by official websites.
The EUCount() function should display the output as:
A or a : 4
M or m: 2
def AMCount( ):
f = open("STORY.txt", "r",)
data = f.read()
count_a = 0
count_m = 0
for i in data :
if i == "a" or i == "A":
count_a += 1
elif i == "m" or i == "M":
count_m += 1
print("A or a :", count_a )
print("M or m:", count_m)
AMCount()
6. Write a program to count the number of upper- case alphabets present in a text file "Article.txt".
count = 0
file = open("Article.txt","r")
sen = file.read()
for i in range ( len(sen) ) :
if sen[ i ].isupper() :
count += 1
7. Write a program that copies one file to another. Have the program read the file names from user ?
data = old.read()
new.write( data )
old.close()
new.close()
8. Write a program that appends the contents of one file to another. Have the program take the filenames
from the user.
file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
old = open( file2 , "r" )
new = open( file1 , "a" )
data = old.read()
new.write( "\n" + data)
old.close()
new.close()
9. 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.
def DISPLAYWORDS() :
file = open("story.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )
file.close()
upper = open("UPPER.txt","w")
lower = open("LOWER.txt" , "w" )
other = open ("OTHER.txt" , "w")
while True :
user = input("Enter a charracter (for exit enter quit ): ")
if user == "quit" or user == "Quit" :
break
elif user.isupper() :
upper.write( user + " " )
elif user.islower( ) :
lower.write( user + " " )
else :
other.write( user + " " )
upper.close()
lower.close()
other.close()
print("Thankyou")
11. 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:
count = 0
file = open("LINES.txt","r")
lst = file.readlines()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("So for number of sentences started with A : ",count)
file.close()
12. Q. Write a program that counts the number of characters up to the first $ in a text file.
file = open("Pathwala.txt","r")
data = file.readlines()
13. Write a program that create an object filout for writing associate it with the filename strs.txt. The code should keep
on writing strings to it as long as the user wants
Example 5.9 or 5.10 – create a file with write mode, check with the user, whether continue (y/n) or not – write or
append the data to the file.
14. Consider the following definition of dictionary Member, write a method in python to write the content in
a pickled file member.dat.
import pickle
file = open("member.dat","wb")
while True :
dic={}
no = int(input("Enter memberbno. :-"))
name = input("Enter name:-")
dic[ "Memberno."] = no
dic["Name"] = name
pickle.dump( dic, file )
user = input("For quit enter quit :-")
if user == "quit":
break
print("Thankyou")
file.close()
15. Consider the following definition of dictionary Staff, write a method in python to search and display
the content in a pickled file staff.dat, where Staffcode key of the dictionary is matching with 'S0105'.
import pickle
file = open("staff.dat", "rb")
found = 0
try :
while True :
staff = pickle.load(file)
if staff [ "Staff Code" ] == 'S0105':
print(staff)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
16. Considering the following definition of dictionary COMPANY, Write a method in Python to search
and display the content in a pickled file COMPANY.DAT, where CompID key of the dictionary is matching
with the value '1005'.
import pickle
file = open("COMPANY.DAT","rb")
found = 0
try :
while True :
Company = pickle.load(file)
if Company [ "CompID" ] == '1005':
print(Company)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
17. Q. Write a function in to search and display details of all trains, whose destination is Delhi from a binary
file TRAIN.DAT. Assuming the binary file is containing the objects of the following dictionary type:
def search() :
file = open("TRAIN.DAT","rb")
found = 0
try :
while True :
Train = pickle.load(file)
if Train [ "To" ] == 'Delhi':
print(Train)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
search()
18. A binary file "Book.dat" has structure [BookNo, Book Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(i) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count
and return number of books by the given Author are stored in the binary file "Book.dat".
import pickle
def CreateFile():
f = open("Book.dat", "wb")
while True :
num = int(input("Enter Book Number :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
pickle.dump( lst, f)
choice = input("For exit (Enter exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
f.close()
def CoutRec():
print("For Searching -")
aut = input("Enter Author :- ")
f = open("Book.dat", "rb")
count = 0
try :
while True:
data = pickle.load(f)
if data[2] == aut :
count += 1
except EOFError:
f.close()
print("Number of Book with Author name", aut , "=", count)
CreateFile()
CoutRec()
19. Write a function Show_words() in python to read the content of a text file "NOTES.TXT" and display
only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
Then the function should display the output as :
This is a sample file.
The file contains many sentences.
import pickle
f = open("NOTES.dat", "rb")
try :
while True:
line = pickle.load(f)
word = line.split()
if len( word ) == 5 :
print( line )
except EOFError:
f.close()
20. Write a Python program to read a given CSV file having tab delimiter.
import csv
file = open( "Pathwalla.txt","r" )
data = csv.reader(file, delimiter = "|")
for i in data :
print(i)
file.close()
21. Write a Python program to write a nested Python list to a csv file in one go. After writing the CSV read
the CSV file and display the content.
import csv
data = csv.reader(file)
for i in data :
print(i)
file.close()
22. Write a function that reads a csv file and creates another csv file with the same content, but with a
different delimiter.
23. Write a function that reads a csv file and creates another csv file with the same content except the lines
beginning with check.
import csv
data = csv.reader(file1)
for i in data :
if i[0][:5] != "check" :
portal_write.writerow( i )
file2.close()
file1 = open( "Pathwalla.txt","r" )
Pathwalla( file1 )
print ("Thank You !!")