I have a text file that will have the contents:
Line 1
,
,
Line 2
,
Line 3
,
Line 4
I would like to create a function that deletes the empty spaces between the lines (marked with , for illustration)
So far, I've created a function with the following code, but nothing happens when I run this:
with open('path/to/file.txt', 'r') as f:
for line in f:
line = line.strip()
Any help is appreciated.
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()
Demo: https://repl.it/@blhsing/KaleidoscopicDarkredPhp
You need to override the file after changing:
with open('path/to/file.txt', 'r') as f:
new_text = '\n'.join([line.strip() for line in f.read().split('\n')] if line.strip())
with open('path/to/file.txt','w') as in_file:
in_file.write(new_text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With