Python File Handling Programs
1. Text – File Programs
2. Binary – File Programs
3. CSV – File Programs (Coming Soon)
Python 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()
Python File Handling Programs
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)
Python File Handling Programs
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()
Python File Handling Programs
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)
Python File Handling Programs
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()
Python File Handling Programs
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()
Python File Handling Programs
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()

Python File Handling Programs
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()
Python File Handling Programs
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
- Write a function addrec() to add a record in a file.
- Write a function disp() to display all the records from the file.
- Write a function specific_disp(room_no) which takes room number as argument and display its details.
- Write a function mod(room_no) which takes room number as argument and modify it’s details.
- 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
- Add Record
- Display All Record
- Display Specific Record
- Modify Record
- 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")
Python File Handling Programs
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( )
Python File Handling Programs
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)
Python File Handling Programs
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)
Disclaimer : I tried to give you the correct coding of โย Python File Handling Programsย โ , but if you feel that there is/are mistakes in the Answers ofย โย Python File Handling Programsย โย given above, you can directly contact me at csiplearninghub@gmail.com. NCERT book and CBSE study material is used to createย โPython File Handling Programs” questions and answers.
Python File Handling Programs
MCQ of Computer Science Chapter Wise
2. Flow of Control (Loop and Conditional statement)
3. 140+ MCQ on Introduction to Python
4. 120 MCQ on String in Python
7. 100+ MCQ on Flow of Control in Python
8. 60+ MCQ on Dictionary in Python
Important Links
100 Practice Questions on Python Fundamentals
120+ MySQL Practice Questions
90+ Practice Questions on List
50+ Output based Practice Questions
100 Practice Questions on String
70 Practice Questions on Loops
70 Practice Questions on if-else
Computer Science Syllabus 2021-2022.
Informatics Practices Syllabus 2021-2022
Class 12 Computer Science Chapter wise MCQ
hey you cannot use same variable twice