您的代码评估代码后的空行 - 因此False
:
您的文件在其最后一行之后包含一个换行符,因此您的代码会检查最后一个数据之后的行,该行未完成您的测试 - 这就是为什么False
无论输入如何您都会得到:
aaa:bb3:3
fff:cc3:4
empty line that does not start with only letters
如果您“特别处理”空行(如果它们出现在末尾),则可以修复它。如果您在填充的之间有一个空行,您False
也会返回:
with open("t.txt","w") as f:
f.write("""aaa:bb3:3
fff:cc3:4
""")
import string
def opener(file):
letters = string.ascii_letters
# Opens a file and creates a list of lines
with open(file) as fi:
res = True
empty_line_found = False
for i in fi:
if i.strip(): # only check line if not empty
if empty_line_found: # we had an empty line and now a filled line: error
return False
#Checks whether any characters in the first column is not a letter
if any(j not in letters for j in i.strip().split(':')[0]):
return False # immediately exit - no need to test the rest of the file
else:
empty_line_found = True
return res # or True
print (opener("t.txt"))
输出:
True
如果你使用
# example with a file that contains an empty line between data lines - NOT ok
with open("t.txt","w") as f:
f.write("""aaa:bb3:3
fff:cc3:4
""")
或者
# example for file that contains empty line after data - which is ok
with open("t.txt","w") as f:
f.write("""aaa:bb3:3
ff2f:cc3:4
""")
你得到: False