【问题标题】:Reading specific line from .txt file从 .txt 文件中读取特定行
【发布时间】:2019-04-05 08:16:22
【问题描述】:

尝试从 .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')

结果:

是的

这条线是假的

【问题讨论】:

  • 读取 == 'True\n' ?
  • 您确定该值为True?你在写什么文件? (True\n)
  • @BornTbeWasted 基于linecache docs,我想说您已经发现了问题。您应该将其发布为答案。
  • @BornTbeWasted 感谢更改 read == 'True\n'
  • 我个人认为read.strip() == 'True' 会更好,但两者都可以。

标签: python readline


【解决方案1】:

这里有一个简单的解释:

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

【讨论】:

    【解决方案2】:

    问题(正如第一条评论所建议的那样是换行符。 在[2]中:阅读 Out[2]: '真\n'

    要修复它,您可以: 如果 read.rstrip() == 'True': print("这条线是真的") 别的: print('这条线是假的')

    另外,只有当您因文件大而遇到性能问题时,我才会使用 linecache。否则使用 open('test.txt').readlines()[-1]

    获取最后一行

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 2011-05-20
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多