If you want to remove blank lines from an existing file without writing to a new one, you can open the same file again in read-write mode (denoted by 'r+'
) for writing. Truncate the file at the write position after the writing is done:
with open('file.txt') as reader, open('file.txt', 'r+') as writer:
for line in reader:
if line.strip():
writer.write(line)
writer.truncate()
CLICK HERE to find out more related problems solutions.