Question

I have the text file:

ACQUIRED  
ALMANAC  
INSULT  
JOKE  
HYMN   
GAZELLE  
AMAZON  
EYEBROWS  
AFFIX  
VELLUM

Unfortunately there is an empty (blank) line under the word VELLUM. I am wondering how do I delete this line in Python and not just simply deleting it from notepad.

Was it helpful?

Solution

You can test if a line is only whitespace pretty easily:

import sys

for line in sys.stdin:
   line = line.strip()
   if line:
      print line

lines that are only whitespace will be empty after the call to strip()

OTHER TIPS

with open("A.txt") as inf, open("B.txt", "w") as outf:
    for line in inf:
        if line.strip():
            outf.write(line)

copies only non-blank lines to a new text file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top