Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Trying to figure out how to write an if cycle to check if a line is empty.

The file has many strings, and one of these is a blank line to separate from the other statements (not a ""; is a carriage return followed by another carriage return I think)

new statement
asdasdasd
asdasdasdasd

new statement
asdasdasdasd
asdasdasdasd

Since I am using the file input module, is there a way to check if a line is empty?

Using this code it seems to work, thanks everyone!

for line in x:

    if line == '
':
        print "found an end of line"

x.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
831 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to ignore lines with only whitespace:

if not line.strip():
    ... do something

The empty string is a False value.

Or if you really want only empty lines:

if line in ['
', '
']:
    ... do  something

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...