Here’s 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:
def remove_extra_spaces(input_file, output_file): with open(input_file, 'r') as file_in: with open(output_file, 'w') as file_out: for line in file_in: line = ' '.join(line.split()) file_out.write(line + '\n') input_file = 'input.txt' output_file = 'output.txt' remove_extra_spaces(input_file, output_file)
In this program, the
remove_extra_spaces function takes two parameters:
input_file (the name of the input file) and
output_file (the name of the output file). It reads the input file line by line, splits each line into words using
.split(), and then joins the words back together using a single space
' '.join(). The resulting line with consecutive blank spaces replaced by a single space is then written to the output file.