Python: 如何检查一行是否为空行

试图弄清楚如何编写一个 if 循环来检查一行是否为空。

该文件有许多字符串,其中一个是空行,用于与其他语句分离(不是 ""; 我认为是一个回车后跟另一个回车)

new statement
asdasdasd
asdasdasdasd


new statement
asdasdasdasd
asdasdasdasd

由于我使用的是文件输入模块,有没有办法检查一行是否为空?

使用这个代码似乎工作,谢谢大家!

for line in x:


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


x.close()
285290 次浏览
line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

If you want to ignore lines with only whitespace:

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

The empty string is a False value.

Or if you really want only empty lines:

if line in ['\n', '\r\n']:
... do  something

You should open text files using rU so newlines are properly transformed, see http://docs.python.org/library/functions.html#open. This way there's no need to check for \r\n.

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
# do something with empty line

I think is more robust to use regular expressions:

import re


for i, line in enumerate(content):
print line if not (re.match('\r?\n', line)) else pass

This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n' as expression