2 回答
TA贡献1833条经验 获得超4个赞
这是一个快速解释:
import linecache
test = open('test.txt', 'w+')
test.write('Test\n')
test.write('True\n')
test.close()
read = linecache.getline('test.txt', 2)
# At this moment read has 'True\n' as value
print(read)
# However print formats the output with the special character. Hence your print
will have a line return try print(read+read) to see
if read == 'True': # This evaluate to False
print("The line is True")
else: #Well this is an else, you should avoid doing so if you have a binary condition. Writing elif read == 'False' is not too bad
print('The line is False')
另外,我的回答是指出为什么它没有按照您的怀疑行事。请参阅有关 str.strip() 的文档:https ://docs.python.org/2/library/stdtypes.html#str.strip
TA贡献2041条经验 获得超4个赞
问题(如第一条评论所建议的那样是换行符。在 [2] 中:读出 [2]:'True\n'
要修复它,您可以: if read.rstrip() == 'True': print("The line is True") else: print('The line is False')
此外,仅当您因大文件而遇到性能问题时,我才会使用 linecache。否则使用 open('test.txt').readlines()[-1]
获取最后一行
添加回答
举报