Python Read Next()
Solution 1:
When you do : f.readlines()
you already read all the file so f.tell()
will show you that you are in the end of the file, and doing f.next()
will result in a StopIteration
error.
Alternative of what you want to do is:
filne = "D:/testtube/testdkanimfilternode.txt"withopen(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a # StopIteration if the last line is also a match.break
Solution 2:
next()
does not work in your case because you first call readlines()
which basically sets the file iterator to point to the end of file.
Since you are reading in all the lines anyway you can refer to the next line using an index:
filne = "in"
with open(filne, 'r+') as f:
lines = f.readlines()
for i in range(0, len(lines)):
line = lines[i]
print line
if line[:5] == "anim ":
ne = lines[i + 1] # you may want to check that i < len(lines)
print' ne ',ne,'\n'break
Solution 3:
lines = f.readlines()
reads all the lines of the file f. So it makes sense that there aren't any more line to read in the file f. If you want to read the file line by line, use readline().
Solution 4:
You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.
filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')
lines = f.readlines() # get all lines as a list (array)# Iterate over each line, printing each line and then move to the next
for line in lines:
print line
f.close()
Solution 5:
A small change to your algorithm:
filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')
while1:
lines = f.readlines()
ifnotlines:
break
line_iter= iter(lines) # here
for line in line_iter: # and here
print line
if (line[:5] == "anim "):
print'next() '
ne = line_iter.next() # and here
print' ne ',ne,'\n'break
f.close()
However, using the pairwise
function from itertools
recipes:
defpairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
you can change your loop into:
for line, next_line in pairwise(f): # iterate over the file directlyprint line
if line.startswith("anim "):
print'next() 'print' ne ', next_line, '\n'break
Post a Comment for "Python Read Next()"