为了账号安全,请及时绑定邮箱和手机立即绑定

从 .txt 文件中读取特定行

从 .txt 文件中读取特定行

largeQ 2021-12-29 20:11:46
尝试从 .txt 文件中读取一行,然后根据该行上的内容编写 if 语句。我写了我认为应该工作的内容,它打印出该行,但 if 语句打印出“此行是假的”import linecachetest = 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')结果:真的这条线是假的
查看完整描述

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


查看完整回答
反对 回复 2021-12-29
?
缥缈止盈

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]

获取最后一行


查看完整回答
反对 回复 2021-12-29
  • 2 回答
  • 0 关注
  • 212 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信