Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete blank/empty lines in text file for Python [closed]

Tags:

python

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.

like image 764
Rutnet Avatar asked Feb 15 '26 15:02

Rutnet


2 Answers

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

like image 94
blhsing Avatar answered Feb 18 '26 04:02

blhsing


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)
like image 33
adir abargil Avatar answered Feb 18 '26 04:02

adir abargil