空白行仅包含\n
或\r\n
或\r
。
tempfile = open(file,"r")
for id,line in enumerate(tempfile):
if(line != "\n" or line != "\r\n" or line !="\r"):
print(id,line)
为什么空行还能打印?
最佳答案
if(line != "\n" or line != "\r\n" or line !="\r"):
应该阅读
if line != "\n" and line != "\r\n" and line !="\r":
即使用 and
而不是 or
。 (我还删除了括号,因为 Python 中不需要它们。)
相同的表达式可以写得更惯用,如下所示:
if line not in {"\n", "\r\n", "\r"}:
或者甚至:
if line.rstrip("\r\n"):
(这会删除所有尾随的 CR 和 LF 字符,然后检查是否还有任何内容。)
关于python - 为什么 line != "\n"或 line != "\r\n"或 line ! ="\r"无法过滤空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231791/