CBSE Class 12 Computer Science Question 121 of 145

File Handling — Question 1

Back to all questions
1
Question

Question 1

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.

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.