Python - Is there a way to trace back the current position of a file object by one line -


i have test file (not python script) contains multiple sequences of form:

testfile (not python script)

#gibberish #gibberish newseq name-and-details 10 20 30 newseq name-and-details 10 20 30 #gibberish #gibberish newseq name-and-details ...and forth 

then, have python script reads file input. each new sequence, new python-list created store contents.

inputfile = open('testfile','r') moreseq = true newline = inputfile.readline() while moreseq:   while (not ('newseq' in newline)):     newline = inputfile.readline()   newlist = []   moreseq = newlist.listentry(inputfile)   listdb.append(newlist) 

but when file object inputfile passed listentry method, wish position point beginning of newseq , not subsequent index:

i.e. wish point newseq #1 line, rather 10 something.

how can trace position of file object 1 line, or fixed measure in lines. believe seek doesn't work in case.

this common problem solved unreading line in following code:

class smartreader(object):     def __init__(self, file):        self.file = file        self.lastline = none     def readline(self):        if self.lastline not none:           ln = self.lastline           self.lastline = none           return ln        return self.file.readline()     def unreadline(self, line):        self.lastline = line                   ...       fd = smartreader(open("file.txt"))     readmore = true     while readmore:        line = fd.readline()        if its_newseq():           fd.unreadline(line)           close_the_previous_sequence()        else:           process_the_line() 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -