100% found this document useful (2 votes)
2K views

Chapter-5-File Handling, Type A, B & C NOTES

The document discusses file handling in Python. It covers opening, reading, and writing to text and binary files. Various file modes like 'r', 'w' and 'a' are described. CSV files are compared to text and binary files. Methods for loading and dumping data to files using pickle are also provided.

Uploaded by

Hemnathpalani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views

Chapter-5-File Handling, Type A, B & C NOTES

The document discusses file handling in Python. It covers opening, reading, and writing to text and binary files. Various file modes like 'r', 'w' and 'a' are described. CSV files are compared to text and binary files. Methods for loading and dumping data to files using pickle are also provided.

Uploaded by

Hemnathpalani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

CHAPTER – 5 – FILE HANDLING

TYPE – A – Short Answer Questions / Conceptual Questions

1. What is the difference between "w" and "a" modes?


"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.
(OR)

2.What is the significance of file-object?


All functions that we perform on a data file are performed through file-objects.
(OR)

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

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

(i) The mentioned file does not exist


(ii) The mentioned file does exist

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

7. What are the advantages of saving data in:

(i) Binary form


(ii) Text form

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.

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.

10. Explain how many file objects would you need to create to manage the following situations:

(a) To process three files sequentially


(b) To merge two sorted files into a third file.

(a) One object are needed.


(b) Three object are needed.
11. Is csv file different from a text file? Why/why not?

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 .

12. Is csv file different from a binary file? Why/why not?

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.

13. Why are csv files popular for data storage?

The csv files are popular because of these reasons :


(i) Easier to create.
(ii) Preferred export and import format for databases and spread-sheets.
(iii) Capable of storing large not amounts of data

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.

TYPE – B – Application Based Questions


1. Q. How are following codes different from one another?
(a)
my_file = open('poem.txt', 'r')
my_file .read()
(b)
my_File = open('poem.txt", "r)
my_file .read(100)
Answer: (a) will read all data of 'poem.txt' , While (b) read only 100 bytes.

2. Q. If the tile 'poemBTH.txt' contains the following poem (by ParamhansaYogananda):


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!

• 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!

While, Output by (b) of Question 1 is that it


will print 100 bytes data of ‘poemBTH.txt’
Output
>>>God made the Earth;
Man made confusing countries.
And their fancy-frozen boundaries.
But with unfou <

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)

Answer = That program reads number of lines present in file "poem.txt".


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

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.

12. What will be the output of the following code?


import pickle
ID = {1: "Ziva", 2: "53050", 3: "IT",4: "38",5: "Dunzo"}
fin = open("Emp.pkl","wb")
pickle.dump(EmpID, fin)
fin.close()
fout = open("Emp.pkl", 'rb')
ID = pickle.load(fout)
print( ID [5] )

Answer : It produce an error that ‘EmpID’ is not defined.


13. What will be the output of the following code?

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)

with open('data.pkl', 'wb') as f :


f.write(list2)

with open('data.pkl', 'rb') as f :


list1 = pickle.load(f)

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 )

with open('data.pkl', 'wb') as f :


pickle.dump(list2 , f )

with open('data.pkl', 'rb') as f :


list1 = pickle.load(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.

15. Identify the error in the following


a) import csv
f = open('attendees1.csv')
csv_f = csv.writer(f)
Ans: Error in line 2, that is program open the file in read mode but in line 3 there is use of writer() function which is
wrong.
b)
import csv
f = open('attendees1.csv')
csv_f = csv.reader()
for row in csv_f:
print(row)

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.

Input – poem.txt output – portal express.txt

2. A file sports.dat contains information in following format : Event ~ Participant


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".

Sports.txt - football atheletics.txt


cricket atheletics
atheletics atheletics
cricket atheletics
throwball
atheletics
cricket
throwball
atheletics
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.
print("Name\t|\tPhone no. ")

file = open("Path Walla.txt", "r")


lst = file.readlines()

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

file = open("Poem.txt", "r")


lst = file.readlines()

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

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

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

print("Number of upper case alphabet : ", count)


file.close()

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

file1 = input("Enter the name of original file :- ")


file2 = input("Enter the name of New file :- : ")

old = open( file1 , "r")


new = open( file2, "w")

data = old.read()
new.write( data )

print(" Program run successfully ")

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)

print("Program run successfully ")

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()

print("Word with length smaller than 3 :- \n")


DISPLAYWORDS()
10. 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.

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:

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.

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()

for i in range( len( data ) ):


for j in range( len( data[ i ] ) ):
if data [ i ][ j ] == "$" :
break

print( "Total number of characters up to the first $ befor = ",i+j )


file.close()

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.

Member = {'MemberNo.': _____, 'Name': _____}

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'.

Staff = {‘Staff Code': _____, 'Name' = _____}

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'.

Company = {'CompID' = ____, 'CName' = ____, ‘Turnover’ = ____}

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:

Train = { 'Tno': ___, ‘From’: ____, 'To' : ____}


import pickle

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

file = open( "Pathwalla.txt","r+" )


lst = eval(input("Enter a nested list :-"))
path_write = csv.writer( file)
path_write.writerows( lst )

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

def Pathwalla( file1 ):


file2 = open( "Portalexpress.txt","w",newline="" )
portal_write = csv.writer( file2 , delimiter = "|")

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 !!")

You might also like