2

In Python, I have an issue where whenever I use the getline() function from linecache module, it won't work at all. Say this was what I had on a text document named hi.txt:

Hi

And say this is what I had on a python program in the same folder/directory:

import linecache

print (linecache.getline("hi.txt", 0))

It would print nothing, just some blank lines of nothing.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
JohnyNich
  • 1,221
  • 3
  • 14
  • 23
  • `linecache.getline` never raises an error: in that case it returns an empty string. Are you sure that you run the program correctly? Can you verify by using `os` that the file exists, etc. – Willem Van Onsem Jan 17 '17 at 13:33
  • Yep, I printed the dictionary using os.listdr() and it's there. – JohnyNich Jan 17 '17 at 13:34
  • Linecache is not really meant for reading user files, it is a helper for caching *source code* for tracebacks. The fact that it never errors and that it always caches contents makes it unusable for general case. Please stay away from it :D – Antti Haapala -- Слава Україні Feb 09 '17 at 11:56

1 Answers1

5

linecache.getline starts at 1.

print (linecache.getline("hi.txt", 1))

does what you expect

>>> help(linecache.getline)
> getline(filename, lineno, module_globals=None)

by convention lineno starts at 1 in any text editor.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219