简体   繁体   中英

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. I wrote what I think should work it prints the line out, but the if statement prints out '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')

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

The problem (as suggested by the first comment is newline. In [2]: read Out[2]: 'True\\n'

To fix it you could either: if read.rstrip() == 'True': print("The line is True") else: print('The line is False')

Also, I'd use linecache only if you experience performance issues due to a large file. Otherwise use open('test.txt').readlines()[-1]

To get the last line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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