简体   繁体   English

从.txt文件读取特定行

[英]Reading specific line from .txt file

Trying to read one line form a .txt file then write an if statement based off whats on that line. 尝试从.txt文件读取一行,然后根据该行的内容编写if语句。 I wrote what I think should work it prints the line out, but the if statement prints out 'this line is false' 我写了我认为应该起作用的内容,它可以打印出该行,但是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')

Outcome: 结果:

True 真正

The line is False 这条线是假的

Here is a quick explanation : 快速说明:

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')

Also , my answer was to point out why it didn't behave according to what you suspected. 另外,我的答案是指出为什么它没有按照您的怀疑表现。 Please see documentation on str.strip() : https://docs.python.org/2/library/stdtypes.html#str.strip 请参阅有关str.strip()的文档: https ://docs.python.org/2/library/stdtypes.html#str.strip

The problem (as suggested by the first comment is newline. In [2]: read Out[2]: 'True\\n' 问题(如第一个注释所建议,是换行符。在[2]中:读出[2]:'True \\ n'

To fix it you could either: if read.rstrip() == 'True': print("The line is True") else: print('The line is False') 要解决此问题,您可以:如果read.rstrip()=='True':print(“该行为True”)否则:print('该行为False')

Also, I'd use linecache only if you experience performance issues due to a large file. 另外,仅当您因文件过大而导致性能问题时,才使用linecache。 Otherwise use open('test.txt').readlines()[-1] 否则使用open('test.txt')。readlines()[-1]

To get the last line 获得最后一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM