从 .txt 文件中读取特定行

尝试从 .txt 文件中读取一行,然后根据该行上的内容编写 if 语句。我写了我认为应该工作的内容,它打印出该行,但 if 语句打印出“此行是假的”


import linecache


test = open('test.txt', 'w+')

test.write('Test\n')

test.write('True\n')

test.close()

read = linecache.getline('test.txt', 2)

print(read)

if read == 'True':

    print("The line is True")

else:

    print('The line is False')

结果:


真的


这条线是假的


largeQ
浏览 214回答 2
2回答

潇潇雨雨

这是一个快速解释:import linecachetest = 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 valueprint(read)# However print formats the output with the special character. Hence your print will have a line return try print(read+read) to seeif 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

缥缈止盈

问题(如第一条评论所建议的那样是换行符。在 [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]获取最后一行
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python