Search code examples
pythonlinecache

Comparing 2 variables when one is retrieved from text file


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")

Solution

  • 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!