Important Text File Questions - Class 12 Computer Science
1. Basic File Operations
Q1. Write a Python program to create a text file and write some lines into it.
with open("[Link]", "w") as f:
[Link]("Hello, this is a test file.\n")
[Link]("This is the second line.")
Q2. Write a program to read a text file line by line and display each line.
with open("[Link]", "r") as f:
for line in f:
print(line, end="")
Q3. Read a text file and count the total number of characters, words, and lines.
with open("[Link]", "r") as f:
lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
print("Lines:", num_lines, "Words:", num_words, "Characters:", num_chars)
2. Searching and Counting
Q1. Count the number of times a specific word appears in a text file.
word_to_count = "test"
count = 0
with open("[Link]", "r") as f:
for line in f:
count += [Link]().split().count(word_to_count.lower())
print("Count:", count)
Q2. Display all lines in a file that contain a specific word.
word = "test"
with open("[Link]", "r") as f:
for line in f:
if [Link]() in [Link]():
print(line, end="")
3. File Modification
Q1. Copy contents of one file to another.
with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
[Link]([Link]())
Q2. Read a text file and write its content in reverse order (line-wise).
with open("[Link]", "r") as f:
lines = [Link]()
with open("[Link]", "w") as f:
for line in reversed(lines):
[Link](line)