Domanda

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.

È stato utile?

Soluzione

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()

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top