Liam McCullough
Liam McCullough

Reputation: 69

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

Upvotes: 0

Views: 106

Answers (2)

Ofer Rahat
Ofer Rahat

Reputation: 878

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

Upvotes: 0

Born Tbe Wasted
Born Tbe Wasted

Reputation: 610

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

Upvotes: 2

Related Questions