Comparing 2 variables when one is retrieved from text file

51 Views Asked by At

I am trying to write code that compares variable b with value retrieved from text file using linecache.getline

The problem is it will never print our "ITS WORKING" because the values never match, even if they do :-(

THE TEXT FILE: In the text file there is only one character and its "a"

Here is the code:

import linecache

b="a" 

a=linecache.getline("TextFile.txt",1)


if a==b:
    print("ITS WORKING")
2

There are 2 best solutions below

4
Keerthana Prabhakaran On BEST ANSWER

You probably need to strip the extra spaces at the end of line that is read.

a=linecache.getline("TextFile.txt",1).strip()


Keerthana:~ kiran$ cat TextFile.txt
a
Keerthana:~ kiran$ py Desktop/test.py
a
ITS WORKING
Keerthana:~ kiran$ 

Hope it helps!

0
timgeb On

According to the documentation, linecache.getline will include the trailing newline character, that's why your match does not work.