File Handling Programs (TEXT FILE)
Q1. Write a program in python to replace all word “the” by another word “them” in a file
“poem.txt”.
Ans.
f=open("poem.txt")
d=f.read()
d=d.replace("the","them")
f.close()
f=open("poem.txt","w")
f.write(d)
f.close()
Q2. Write a program in python to replace a character by another character in a file
“story.txt”. (Accept both the characters from the user)
Ans. f = open("story.txt", "r")
d = f.read()
ch = input("Enter character to be replaced")
ch1 = input("Enter character that will replaced")
d = d.replace(ch, ch1)
f.close()
f = open("story.txt", "w")
f.write(d)
f.close()
Q3. Write a program in python to replace all the ‘a’ by ‘@’ in a file “data.txt”.
Ans. f = open("data.txt", "r")
d = f.read()
d = d.replace('a', '@')
f.close()
f=open("data.txt", "w")
f.write(d)
f.close()
Q4. Write a program in python to read file “data.txt” and display only those lines whose
length is more than 40 characters.
Ans. f=open("data.txt")
d=f.readlines()
for i in d:
if len(i)>40:
print(i)
Q5. Write a program in python to remove all duplicate lines from the file “story.txt”.
Ans. f = open("story.txt", "r")
d = f.readlines()
m=[]
for i in d:
if i not in m:
m.append(i)
print(m)
f.close()
f = open("story.txt", "w")
for i in m:
f.write(i)
f.close()
Q6. Write a program in python to display only unique words from the file “story.txt”.
Ans. f = open("story.txt", "r")
d = f.read()
d = d.split()
str = " "
m = []
for i in d:
if i not in str:
str=str+i
print(i, end=" ")
f.close()
Q7. Write a program in python to count the frequency of each vowels in a file “task.txt”.
Ans. f = open("task.txt", "r")
d = f.read()
va=ve=vo=vu=vi=0
for i in d:
if i=='a' or i=='A':
va=va+1
if i=='e' or i=='E':
ve=ve+1
if i=='i' or i=='I':
vi=vi+1
if i=='o' or i=='O':
vo=vo+1
if i=='u' or i=='U':
vu=vu+1
print("Frequency of vowel \"a\" is", va)
print("Frequency of vowel \"e\" is", ve)
print("Frequency of vowel \"i\" is", vi)
print("Frequency of vowel \"o\" is", vo)
print("Frequency of vowel \"u\" is", vu)
Q8. Write a program in python to count those words whose length is more than 7
characters in a file “story.txt”.
Ans. f=open("story.txt", "r")
d=f.read()
d=d.split()
c=0
for i in d:
if len(i)>7:
c=c+1
print("Total words are :", c)
Q9. Write a program in python to count those lines from the file “div.txt” which are starting
from ‘T’ or ‘M’.
Ans. f=open("div.txt", "r")
d=f.readlines()
c=0
for i in d:
if i[0] == 'M' or i[0] == 'T':
c=c+1
print("Total lines are :", c)
Q10. Write a program in python to count those lines from the file “div.txt” which are not
starting from ‘M’.
Ans. f=open("div.txt")
d=f.readlines()
c=0
for i in d:
if i[0] != 'M':
c=c+1
print("Total lines are :", c)
Q11. Write a program in python to display those words from a file “image.txt” which are
ending from alphabet ‘m’.
Ans. f=open("image.txt")
d=f.read()
d=d.split()
c=0
for i in d:
if i[-1]=='m':
c=c+1
print("Total words are :", c)
Q12. Write a program in python to read all lines of file “data.txt” using readline() only.
Ans. f=open("data.txt", "r")
str = " "
while str:
str = f.readline()
print(str, end = "")
f.close()
Q13. Write a program in Python to copy the entire content from file “data.txt” to “story.txt”
Ans. f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.read()
f1.write(d)
f.close()
f1.close()
Q14. Write a program in Python to copy the alternate lines from file “data.txt” to “story.txt”
Ans. f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.readlines()
for i in range(len(d)):
if i%2==0:
f1.write(d[i])
f.close()
f1.close()
Q15. Write a program in Python to read the entire content from file “data.txt” and copy the
contents to “story.txt” in upper case.
Ans. f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.readlines()
for i in d:
f1.write(i.upper())
f.close()
f1.close()
Q16. Write a program in Python to read the entire content from file “data.txt” and copy only
those words to “story.txt” which start from vowels.
Ans.
f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.read()
d = d.lower()
word = d.split()
for i in word:
if i[0] in ['a', 'e', 'i', 'o', 'u']:
f1.write(i)
f.close()
f1.close()
Q17. Write a program in Python to read the entire content from file “data.txt” and copy only
those words in separate lines to “story.txt” which are starting from lower case alphabets .
Ans. f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.read()
word = d.split()
for i in word:
if i[0].islower():
f1.write(i)
f1.write("\n")
f.close()
f1.close()
Q18. Write a program in Python to read file “data.txt” and copy only those lines to
“story.txt” which are starting from alphabets “A” or “T”.
Ans. f = open("data.txt", "r")
f1 = open("story.txt", "w")
d = f.readlines()
for i in d:
if i[0] == "A" or i[0] == "T":
f1.write(i)
f.close()
f1.close()
Q19. Write a program in Python which display the longest word from file “star.txt”
Ans. f = open("star.txt", "r")
d = f.read()
L = d.split()
longword = " "
for i in L:
if len(i) > len(longword):
longword = i
print("longest word is ,",longword)
f.close()
Q20. Write a program in Python which display the longest line from file “star.txt”
Ans. f = open("star.txt", "r")
d = f.readlines()
longline = " "
for i in d:
if len(i) > len(longline):
longline = i
print("longest line is : ", longline)
f.close()
Q21. Write a program in Python to read the file “star.txt” and display the entire content
after removing leading and trailing spaces.
Ans. f = open("star.txt", "r")
d = f.readlines()
for i in d:
print(i.strip())
f.close()
Q22. Write a program in python that read the content from file “sumit.txt” and display all
numbers.
Ans. f = open("sumit.txt", "r")
d = f.read()
for i in d:
if i.isdigit():
print(i)
f.close()
Q23. Write a program in Python that display the second and second last line from the file
“life.txt”
Ans. f = open("data.txt", "r")
d = f.readlines()
print("Second line is :",d[1])
print("Second last line is :",d[-2])
f.close()
Python File Handling Programs-Binary File
Q24. Consider a binary file “data.dat” which stores the record of “Hotel” in the form of list
containing Room_no, Price, Room_type. Do the following task in a file
1. Write a function addrec() to add a record in a file.
2. Write a function disp() to display all the records from the file.
3. Write a function specific_disp(room_no) which takes room number as argument and
display its details.
4. Write a function mod(room_no) which takes room number as argument and modify
it’s details.
5. Write a function del(room_no) which takes room number as argument and delete
it’s record from file “data.dat”
Ans 1. import pickle
def addrec():
L=[ ]
f=open("data.dat","ab")
rn = int(input("Enter Room Number"))
pr = int(input("Enter the price of room"))
rt = input("Enter the type of room")
L = [rn, pr, rt]
pickle.dump(L, f)
print("Record added in the file")
f.close()
addrec()
______________________________________________________________
Ans 2. import pickle
def disp():
try:
f=open("data.dat","rb")
while True:
d=pickle.load(f)
print(d)
except:
f.close()
disp()
_____________________________________________________________________
Ans 3.
import pickle
def specific_rec(rno):
try:
f1=open("data.dat","rb")
while True:
d=pickle.load(f1)
if rno==d[0]:
print(d)
except:
f1.close()
rno=int(input("Enter Room number to search"))
specific_rec(rno)
______________________________________________________________________
Ans 4.
import pickle
import os
def mod():
roll = int(input("Enter room number whose record you want to Modify:"))
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll == d[0]:
d[1]=int(input("Enter modified price"))
d[2]=input("Enter modified room type")
pickle.dump(d,f)
except:
print("Record Updated")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
mod()
________________________________________________________________________
Ans 5.
import pickle
import os
def delete():
roll = int(input("Enter room number whose record you want to delete:"))
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll != d[0]:
pickle.dump(d,f)
else:
found = 1
except:
print("Record Deleted")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
delete()
Q25. Write a menu driven program which shows all operations on Binary File
1. Add Record
2. Display All Record
3. Display Specific Record
4. Modify Record
5. Delete Record
Use “data.dat” file which stores the record of “Hotel” in the form of list containing
Room_no, Price, Room_type.
Ans.
import pickle
import os
def main_menu():
print("1. Add a new record")
print("2. Display all record")
print("3. Display Specific record")
print("4. Modify a record")
print("5. Delete a record")
print("6. Exit")
ch = int(input("Enter your choice:"))
if ch==1:
addrec()
elif ch==2:
disp()
elif ch==3:
specific_rec()
elif ch==4:
mod()
elif ch==5:
del()
elif ch==6:
print("Bye")
else:
print("Invalid Choice.")
def addrec():
L=[ ]
f=open("data.dat","ab")
rn = int(input("Enter Room Number"))
pr = int(input("Enter the price of room"))
rt = input("Enter the type of room")
L = [rn, pr, rt]
pickle.dump(L, f)
print("Record added in the file")
f.close()
def disp():
try:
f=open("data.dat","rb")
while True:
d=pickle.load(f)
print(d)
except:
f.close()
def specific_rec():
rno=int(input("Enter Room number to search"))
try:
f1=open("data.dat","rb")
while True:
d=pickle.load(f1)
if rno==d[0]:
print(d)
except:
f1.close()
def mod():
roll = int(input("Enter room number whose record you want to modify:"))
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll == d[0]:
d[1]=int(input("Enter modified price"))
d[2]=input("Enter modified room type")
pickle.dump(d,f)
except:
print("Record Updated")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
def delete():
roll = int(input("Enter room number whose record you want to delete:"))
try:
file = open("data.dat","rb+")
f=open("temp1.dat","wb")
while True:
d = pickle.load(file)
if roll != d[0]:
pickle.dump(d,f)
except:
print("Record Deleted")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
Q26. Write a function disp75() in Python to display only those records of students from
file “school.dat” who scored more than 75 percent marks. Structure stored in “school.dat”
is in the form of list containing information like [rollno, name, class, percentage]
Ans.
def disp75():
f=open("school.dat", "rb")
try:
while True:
d=pickle.load(f)
if d[3]>75:
print("Roll Number : ", d[0], "\n")
print("Name : ", d[1], "\n")
print("Class : ", d[2], "\n")
print("Percentage : ", d[3], "\n")
except:
f.close()
disp75()
Q27. Write a function dispname() in Python which will display only names of all the students
from file “school.dat”. Structure stored in “school.dat” is in the form of list containing
information like [rollno, name, class, percentage]
Ans.
def dispname():
f=open("school.dat","rb")
try:
while True:
d=pickle.load(f)
print("Name : ", d[1],"\n")
except:
f.close()
dispname()
Q28. Write a function disp12() in Python which will display records of class 12th students
from file “school.dat”. Structure stored in “school.dat” is in the form of list containing
information like [rollno, name, class, percentage]
Ans.
def disp12( ):
f=open("school.dat", "rb")
try:
while True:
d=pickle.load(f)
if int(d[2]) == 12:
print("Roll Number : ", d[0],"\n")
print("Name : ", d[1],"\n")
print("Class : ", d[2],"\n")
print("Percentage : ", d[3],"\n")
except:
f.close( )
disp12( )
Q29. Write a function search(name) in Python which will display record of a student from
file “school.dat” whose name is passed as an argument. Structure stored in “school.dat” is in
the form of list containing information like [rollno, name, class, percentage]
Ans.
def search(nm):
f=open("school.dat","rb")
try:
while True:
d=pickle.load(f)
if d[1].lower() == nm.lower():
print("Roll Number : ", d[0],"\n")
print("Name : ", d[1],"\n")
print("Class : ", d[2],"\n")
print("Percentage : ", d[3],"\n")
except:
f.close()
nm=input("Enter name of the student")
search(nm)
Q30. Write a function rem() in Python which will delete the records of students from file
“school.dat” who scored less than 30 percent marks. Structure of “school.dat” is in the form
of list containing information like [rollno, name, class, percentage].
Ans.
import pickle
import os
def rem():
f=open("school.dat", "rb")
f1=open("temp.dat", "wb")
try:
while True:
d=pickle.load(f)
if(d[3])>30:
pickle.dump(d, f1)
except:
f.close()
f1.close()
os.remove("school.dat")
os.rename("temp.dat", "school.dat")
rem()
Q31. Write a function modi_rec(rno) in Python which will modify the records of students
from file “school.dat” whose Roll number is passed as an argument. Structure of
“school.dat” is in the form of list containing information like [rollno, name, class,
percentage].
Ans.
def modi_rec(rn):
f=open("school.dat","rb")
f1=open("temp.dat","wb")
try:
while True:
d=pickle.load(f)
if(d[0])!=rn:
pickle.dump(d, f1)
else:
nm=input("Enter name of student: ")
cls=input("Enter Class of student: ")
per=int(input("Enter percentage of student: "))
L=[rn, nm, cls, per]
pickle.dump(L,f1)
except:
f.close()
f1.close()
os.remove("school.dat")
os.rename("temp.dat", "school.dat")
rn = int(input("Enter roll number of student whose record you want to modify"))
modi_rec(rn)
Q32. Write a function disp_author(name) in Python to display detail of author whose name
is passed as an argument from “book.dat”. Structure stored in file is in the form of [Bookid,
Price, Author Name, Subject]
Ans.
import pickle
def disp_author(name):
try:
f1=open("book.dat","rb")
while True:
d=pickle.load(f1)
if name==d[2]:
print(d)
except:
f1.close()
author_name = input("Enter Author Name")
disp_author(author_name)
Q33. Write a function addmarks(name) in Python which will add the marks of all the
subjects of a student whose name is passed as an argument from “marks.dat”. Structure of
“marks.dat” is [Name, Chem_marks, Phy_marks, CS_marks, Eng_marks]
Ans.
import pickle
def addmarks(name):
try:
f1=open("marks.dat","rb")
while True:
d=pickle.load(f1)
if name==d[0]:
s=d[1]+d[2]+d[3] + d[4]
print("Total marks of ",name, "is", s)
except:
f1.close()
s_name = input("Enter Student Name")
addmarks(s_name)
Q34. Write a function addval() in Python which will add the record of a mobile in
“mobile.dat”. Structure of “mobile.dat” is [Mobile id, Mobile brand, Model No., Price]
Ans. import pickle
def addval():
L=[ ]
f=open("mobile.dat","ab")
mid = int(input("Enter Mobile id"))
mb = input("Enter the brand of mobile")
mn = input("Enter the model number of mobile")
pr = int(input("Enter the price of Mobile"))
L = [mid, mb, mn, pr]
pickle.dump(L, f)
print("Record added in the file")
f.close()
addval()
Q35. Write a function disp_mob(model no.) in Python which will display the record of a
mobile from “mobile.dat” whose model number (integer type) is passed as an argument.
Structure of “mobile.dat” is [Mobile id, Mobile brand, Model No., Price]
Ans.
import pickle
def disp_mob(modno):
try:
f1=open("mobile.dat","rb")
while True:
d=pickle.load(f1)
if modno==d[2]:
print(d)
except:
f1.close()
mod_number = int(input("Enter the model number of mobile"))
disp_mob(mod_number)
Python CSV File Handling
CSV (Comma-separated values) is a common data exchange format used by the
applications to produce and consume data.
A CSV file is a simple text file where each line contains a list of values (or fields)
delimited by commas (mostly), but you will encounter CSV files where data is
delimited using tab (\t) or pipe (|) or any other character.
The first line of the CSV file represents the header containing a list of column
names in the file.
CSV file is commonly used to represent tabular data
See the following table
Name Class Section
Amit X A
Sumit XI B
Ashish XII C
The above table will be stored in CSV format as follows:
If the values in the table contain comma(,) like below in column Address
Then in CSV it will be stored like below (Values containing comma will be enclosed in
double quotes)
Python Provides CSV module to work with csv file: Main Functions are:
1. reader()
2. writer()
3. DictReader()
4. DictWriter()
1. reader() function : This function help us to read the csv file. This function takes a
file object and returns a _csv.reader object that can be used to iterate over the
contents of a CSV file.
How to read entire data from data.csv file?
Let we try to read the following file ie “data.csv”
data.csv
CODING OUTPUT
[‘Name’ , ‘Class’ , ‘Subject’]
import csv
[‘Amit’ , ‘XII’ , ‘ CS’]
f = open(“data.csv”, ‘r’)
[‘Sumit’ , ‘X’ , ‘IP’]
row = csv.reader(f)
Notice that each line in the CSV file is returned as a list of
for i in row :
strings
print(i)
Line-wise explanation of the code
1. The first line is importing a csv module.
2. This line is opening a file (data.csv) in reading mode and f is file object or file
handle.
3. This line is returning a csv.reader object that can be used to iterate over csv file
contents
4. We are using loop on the object which is returned by the previous line
CODING OUTPUT
import csv
f = open(“data.csv”, ‘r’)
Returns the memory address where csv.reader object is
row = csv.reader(f)
stored
print(row)
How to read specific column from data.csv?
CODING OUTPUT Actual Data of File
import csv
f = open(“data.csv”, ‘r’)
row = csv.reader(f) Name Subject [‘Name’ , ‘Class’ , ‘Subject’]
for i in row : Amit CS [‘Amit’ , ‘XII’ , ‘ CS’]
print(i[0] , i[2]) Sumit IP [‘Sumit’ , ‘X’ , ‘IP’]
The above code is reading first and
third column from “data.csv” file
If you want to skip the First Row (header of the table)
CODING OUTPUT Actual Data of File
import csv [ ‘Amit’ , ‘CS’] [‘Name’ , ‘Class’ ,
f = open(“data.csv”, ‘r’) [‘Sumit’ , ‘IP’ ] ‘Subject’]
row = csv.reader(f) [‘Amit’ , ‘XII’ , ‘ CS’]
next(row) [‘Sumit’ , ‘X’ , ‘IP’]
for i in row :
print(i[0] , i[2])
next () function will jump to the next
row.
import csv
f = open(“data.csv”, ‘r’)
row = csv.reader(f)
next(row)
next(row) [‘Sumit’ , ‘IP’ ]
for i in row : [‘Name’ , ‘Class’ ,
print(i[0] , i[2]) ‘Subject’]
[‘Amit’ , ‘XII’ , ‘CS’]
If we use the next() function two [‘Sumit’ , ‘X’ , ‘IP’]
times
then it will skip two lines from
beginning
If there is any other delimiter other than comma like in the following file
CODING OUTPUT
import csv
[‘id’ , ‘name’ , ’email’ , ‘salary’]
f = open(“data.csv”, ‘r’)
[‘1’ , ‘Amit’ , ‘amit@mail.com’ , ‘25000’]
row = csv.reader(f, delimiter = ‘l’)
[‘2’ , ‘Sumit’ , ‘sumit@mail.com’ , ‘30000’]
for i in row :
[‘3’ , ‘Ashu’ , ‘ashu@mail.com’ , ‘40000’]
print(i)
2. writer() function : This function help us to write data in a csv file. It accepts the
same argument as the reader() function but returns a writer object
(i.e _csv.writer)
There are two main methods used in writing in csv file
1. writerow()
2. writerows()
Example using writerow()
CODING DATA.CSV
import csv
f = open(“data.csv”, ‘w’)
wr = csv.writer(f) Name , Class
wr.writerow([‘Name’ , ‘Class’]) ‘Amit’ , ‘XII’
wr.writerow([‘Amit’ , ‘XII’])
f.close( )
Example using writerows()
CODING DATA.CSV
import csv
Name, Class, Subject
fields = [‘Name’ , ‘Class’ , ‘Subject’]
Amit, XII, CS
rows = [[“Amit” , ‘XII’ , ‘CS’] ,
Sumit, X, IP
[‘Sumit’ , ‘X’ , ‘IP’] ,
[‘Ashu’ , ‘XI’ , ‘CS’]] Ashu, XI, CS
f = open(“data.csv” , ‘w’ , newline = ‘ ‘)
wr = csv.writer(f)
wr.writerow(fields)
wr.writerows(rows)
f.close
Python CSV File
Reading a CSV file with DictReader:
This function(DictReader) is working similar to reader(). This function return lines as a
dictionary instead of list.
CODING OUTPUT data.csv
import csv
f = open(“data.csv” , ‘r’) Name, Class
{‘Name’ : ‘Amit, ‘Class’ : ‘XII’}
row = csv.DictReader(f) Amit, XII
{‘Name’ : ‘Sumit, ‘Class’ : ‘X’}
for i in row: Sumit, X
{‘Name’ : ‘Ashu, ‘Class’ : ‘XI’}
print(i) Ashu, XI
Python CSV File
This CSV file has no header. So we have to provide field names via
the fieldnames parameter
CODING
import csv
f = open(“data.csv” , ‘r’)
row = csv.DictReader(f, fieldnames = [‘Name’ , ‘Class’ , ‘Subject’])
for i in row:
print(i)
OUTPUT
{‘Name’ : ‘Amit, ‘Class’ : ‘XII’ , ‘Subject’ : ‘CS’}
{‘Name’ : ‘Sumit, ‘Class’ : ‘X’ , ‘Subject’ : ‘IP’}
{‘Name’ : ‘Ashu, ‘Class’ : ‘XI’ , ‘Subject’ : ‘CS’}
data.csv
Amit, XII, CS
Sumit, X, IP
Ashu, XI, CS