Computer Science
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
Related Questions
Identify the error in the following code.
import csv f = open('attendees1.csv') csv_f = csv.reader() for row in csv_f: print(row)
Identify the error in the following code.
import pickle data = ['one', 2, [3, 4, 5]] with open('data.dat', 'wb' : pickle.dump(data)
A file sports.dat contains information in following format:
Event - Participant
Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is "Atheletics".A file contains a list of telephone numbers in the following form:
Arvind 7258031 Sachin 7259197
The names contain only one word, the names and telephone numbers are separated by white spaces. Write program to read a file and display its contents in two columns.