python - change direction of reading file? -


i have adafruit lcd screen , want buttons able navigate down , lines text text file.

i have spent day trying work out problem.

so far have :

if lcd.is_pressed(lcd.up):     lcd.clear()     text = txt.readline()     lcd.message(("%s") % text)     print "%s" % text     time.sleep (0.5) elif lcd.is_pressed(lcd.down):     lcd.clear()     # need can read line last or somthing     text = txt.readline()      lcd.message(("%s") % text)     print "%s" % text     time.sleep (0.5) 

i have bits drive lcd working can go down file.

python provides linecache module which, while built-in enable friendly tracebacks, works fine text files. splits difference between reading lines memory , reading file live, , design ideal scenario you're considering (where you're moving between adjacent lines, aiding caching).

import linecache  ...  lineno = 0 txtfilename = '...'  ...  if lcd.is_pressed(lcd.up) or lcd.is_pressed(lcd.down):     lineno += 1 if lcd.is_pressed(lcd.up) else -1  # these numbers match behavior in example, think may want reverse them, goes 1 line...     lcd.clear()     text = linecache.getline(txtfilename, lineno)     lcd.message(("%s") % text)     print "%s" % text     time.sleep (0.5) 

Comments