File Handling Questions and Answers - Class XII
1. Write a Python program to read a text file and count the number of words in it.
# 1. Count number of words in a file
with open("file.txt", "r") as f:
text = f.read()
words = text.split()
print("Total words:", len(words))
2. Write a program to copy contents of one file into another.
# 2. Copy contents of one file to another
with open("source.txt", "r") as src, open("dest.txt", "w") as dst:
dst.write(src.read())
3. Write a program to read a file and display all lines that start with a vowel.
# 3. Display lines starting with a vowel
with open("file.txt", "r") as f:
for line in f:
if line[0].lower() in 'aeiou':
print(line, end="")
4. Write a program to write 5 lines into a text file taken as input from the user.
# 4. Write 5 user input lines to a file
with open("file.txt", "w") as f:
for _ in range(5):
line = input("Enter line: ")
f.write(line + "\n")
5. Write a program to read a binary file and count the total number of bytes.
# 5. Count total bytes in a binary file
with open("binary.dat", "rb") as f:
data = f.read()
print("Total bytes:", len(data))
6. Write a program to store a list of names in a file and then read and print them.
# 6. Store list of names and print them
names = ["Alice", "Bob", "Charlie"]
with open("names.txt", "w") as f:
for name in names:
f.write(name + "\n")
with open("names.txt", "r") as f:
print(f.read())
7. Write a program to display the last line of a text file.
# 7. Display last line of text file
with open("file.txt", "r") as f:
lines = f.readlines()
print("Last line:", lines[-1])
8. Read a file and display the frequency of each word.
# 8. Word frequency
from collections import Counter
with open("file.txt", "r") as f:
words = f.read().split()
freq = Counter(words)
print(freq)
9. Write a program to sort lines of a text file alphabetically and write them to another file.
# 9. Sort lines alphabetically
with open("file.txt", "r") as f:
lines = sorted(f.readlines())
with open("sorted.txt", "w") as f:
f.writelines(lines)
10. Write a program to reverse the contents of each line in a file.
# 10. Reverse contents of each line
with open("file.txt", "r") as f:
lines = f.readlines()
with open("reversed.txt", "w") as f:
for line in lines:
f.write(line[::-1])
11. Write a program to count the number of uppercase and lowercase letters in a file.
# 11. Count uppercase and lowercase letters
with open("file.txt", "r") as f:
text = f.read()
upper = sum(1 for c in text if c.isupper())
lower = sum(1 for c in text if c.islower())
print("Uppercase:", upper, "Lowercase:", lower)
12. Write a Python program to read a file and print only those lines which contain the word
'Python'.
# 12. Print lines containing 'Python'
with open("file.txt", "r") as f:
for line in f:
if "Python" in line:
print(line, end="")
13. Write a Python program to display all lines from a file that are longer than 5 characters.
# 13. Lines longer than 5 characters
with open("file.txt", "r") as f:
for line in f:
if len(line.strip()) > 5:
print(line, end="")
14. Write a Python program to count the number of blank spaces and newline characters in a
text file.
# 14. Count blank spaces and newline characters
with open("file.txt", "r") as f:
text = f.read()
print("Spaces:", text.count(" "), "Newlines:", text.count("\n"))
15. Create a file students.txt and store names and marks of 5 students. Then display students
with marks above 75.
# 15. Display students with marks > 75
with open("students.txt", "w") as f:
for _ in range(5):
name = input("Name: ")
marks = input("Marks: ")
f.write(name + "," + marks + "\n")
with open("students.txt", "r") as f:
for line in f:
name, marks = line.strip().split(",")
if int(marks) > 75:
print(name, marks)
16. Write a Python program to remove all punctuation marks from a text file.
# 16. Remove punctuation marks
import string
with open("file.txt", "r") as f:
text = f.read()
for p in string.punctuation:
text = text.replace(p, "")
with open("nopunct.txt", "w") as f:
f.write(text)
17. Write a program to read a text file and count the number of vowels and consonants.
# 17. Count vowels and consonants
with open("file.txt", "r") as f:
text = f.read().lower()
vowels = sum(1 for c in text if c in "aeiou")
consonants = sum(1 for c in text if c.isalpha() and c not in "aeiou")
print("Vowels:", vowels, "Consonants:", consonants)
18. Write a Python program to write 5 integers to a binary file and then read and display
them.
# 18. Write and read 5 integers to/from binary file
import pickle
with open("ints.dat", "wb") as f:
pickle.dump([1, 2, 3, 4, 5], f)
with open("ints.dat", "rb") as f:
print(pickle.load(f))
19. Write a program to store a list of employee records (empno, name, salary) into a binary
file using pickle.
# 19. Store employee records using pickle
import pickle
employees = [(1, "John", 50000), (2, "Jane", 60000)]
with open("emp.dat", "wb") as f:
pickle.dump(employees, f)
20. Write a program to search for an employee record by empno in a binary file.
# 20. Search employee by empno
import pickle
with open("emp.dat", "rb") as f:
employees = pickle.load(f)
empno = int(input("Enter empno: "))
for e in employees:
if e[0] == empno:
print(e)
21. Write a program to delete a student record (by roll number) from a binary file.
# 21. Delete student by roll number
import pickle
with open("students.dat", "rb") as f:
students = pickle.load(f)
roll = int(input("Roll no to delete: "))
students = [s for s in students if s[0] != roll]
with open("students.dat", "wb") as f:
pickle.dump(students, f)
22. Create a CSV file with fields roll, name, marks and write 5 records.
# 22. Create CSV file with 5 records
import csv
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["roll", "name", "marks"])
for _ in range(5):
roll = input("Roll: ")
name = input("Name: ")
marks = input("Marks: ")
writer.writerow([roll, name, marks])
23. Read the CSV file and display all records where marks > 90.
# 23. Display records with marks > 90
import csv
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
if int(row["marks"]) > 90:
print(row)
24. Modify the marks of a student given their roll number in the CSV file.
# 24. Modify marks of student by roll number
import csv
rows = []
roll_to_modify = input("Enter roll to modify: ")
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
if row["roll"] == roll_to_modify:
row["marks"] = input("New marks: ")
rows.append(row)
with open("students.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["roll", "name", "marks"])
writer.writeheader()
writer.writerows(rows)