从.txt文件读取特定行

时间:2019-04-05 08:16:23

标签: python readline

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

select gameid,palyerid, 
max(case when event_desc='Shot' then count end) as shot,
max(case when event_desc='Miss' then count end) as Miss,
max(case when event_desc='Rebound' then count end) as Rebound,
max(case when event_desc='Foul' then count end) as Foul,
max(case when event_desc='Assist' then count end) as Assist,
------
from table_name group by  gameid,palyerid

结果:

该行为False

2 个答案:

答案 0 :(得分:2)

这里是一个简短的解释:

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

答案 1 :(得分:0)

问题(如第一个评论所建议,是换行符。     在[2]中:阅读     出[2]:“真\ n”

要解决此问题,您可以:     如果read.rstrip()=='真':         print(“这条线是真实的”)     其他:         print('该行为假')

此外,仅当您由于文件太大而遇到性能问题时,才使用线缓存。否则使用     open('test.txt')。readlines()[-1]

获取最后一行