从 .txt 文件中读取特定行
Reading specific line from .txt file
尝试从 .txt 文件中读取一行,然后根据该行的内容编写 if 语句。我写了我认为应该工作的内容,它打印出行,但是 if 语句打印出 'this line is false'
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')
结果:
正确
这条线是假的
这里有一个简单的解释:
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]:'True\n'
要修复它,您可以:
如果 read.rstrip() == 'True':
打印("The line is True")
别的:
打印('The line is False')
此外,只有当您因大文件而遇到性能问题时,我才会使用 linecache。否则使用
打开('test.txt').readlines()[-1]
获取最后一行
尝试从 .txt 文件中读取一行,然后根据该行的内容编写 if 语句。我写了我认为应该工作的内容,它打印出行,但是 if 语句打印出 'this line is false'
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')
结果:
正确
这条线是假的
这里有一个简单的解释:
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]:'True\n'
要修复它,您可以: 如果 read.rstrip() == 'True': 打印("The line is True") 别的: 打印('The line is False')
此外,只有当您因大文件而遇到性能问题时,我才会使用 linecache。否则使用 打开('test.txt').readlines()[-1]
获取最后一行