Any return function in python?

Sorry guys!!! sorry. I am new to Python. I am writing the following code:

for line in file: if StartingMarker in line: # Here: I want to push back 'line' back in 'file' for nextline in file: if EndingMarker in line: # Do some Operation print "Done" 

How can I push the "line" back to the "file"?

Thanks at Advance.

+4
source share
4 answers

Do not back down, harvest.

 def starttoend(it): for line in it: if 'START' in line: yield line break for line in it: yield line if 'END' in line: break l = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb'] i = iter(l) for line in starttoend(i): print line 

Just use an iterator if you need more sequences.

+4
source

There is no iterator that I know that you can start an iteration and then click on the element that was returned to the iterator. But you can create a new iterator ( itertools.chain ) that iterates over the current element and the rest of the elements of the original iterator. Sort of:

 import itertools with open('some-input-file') as f: it = iter(f) for line in it: if StartingMarker in line: it2 = itertools.chain(iter([line]), it) for nextline in it2: if EndingMarker in nextline: # Do some Operation 
+1
source
 for line in file: if StartingMarker in line and EndingMarker in line: # look ma! no need to push back 

EDIT:

 for line in file: if StartingMarker in line: # do some operation if EndingMarker in line: # do some other operation 
0
source
 for line in file: if StartingMarker in line: if endingmarker in line: #do operation else: for nextline in file: if EndingMarker in line: # Do some Operation print "Done" 
0
source

All Articles