1

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")
Bob
  • 347
  • 2
  • 3
  • 12

2 Answers2

2

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

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

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!

Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23