Class - 12 CBSE Computer Science Important File Handling Questions 2025
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.
Python File Handling
10 Likes
Answer
Let the file "input.txt" include the following sample text:
In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.
with open("input.txt", 'r') as f:
with open("output.txt", 'w') as fout:
for line in f:
modified_line = ' '.join(line.split())
fout.write(modified_line + '\n')
The file "output.txt" includes following text:
In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.
Answered By
7 Likes