Like unread lines in python

I am new to Python (2.6) and have a situation where I need not to read a line that I just read from a file. Here is basically what I do.

for line in file: print line file.seek(-len(line),1) zz = file.readline() print zz 

However, I notice that "zz" and "line" do not match. Where am I going wrong?

Thanks.

+7
source share
4 answers

I do not think that for line in file: and seek make a good combination. Try something like this:

 while True: line = file.readline() print line file.seek(-len(line),1) zz = file.readline() print zz # Make sure this loop ends somehow 
+10
source

You simply cannot mix iterators and seek() this way. You must choose one method and stick to it.

+4
source

You can combine row iteration with the .seek() operation:

 for i, line in enumerate(iter(f.readline, ''), 1): print i, line, if i == 2: # read 2nd line two times f.seek(-len(line), os.SEEK_CUR) 

If the file contains:

 a b c 

Then the output will be:

 1 a 2 b 3 b 4 c 
+2
source

untested. Basically, you want to save cache for "unread" lines. Each time you read a line, if there is something in the cache, first remove it from the cache. If there is nothing in the cache, read the new line from the file. It's rude, but you need to go.

 lineCache = [] def pushLine(line): lineCache.append(line) def nextLine(f): while True: if lineCache: yield lineCache.pop(0) line = f.readline() if not line: break yield line return f = open('myfile') for line in nextLine(f): # if we need to 'unread' the line, call pushLine on it. The next call to nextLine will # return the that same 'unread' line. if some_condition_that_warrants_unreading_a_line: pushLine(line) continue # handle line that was read. 
+1
source

All Articles