next()
in python does not work. What is an alternative to reading next line in Python? Here is a sample:
filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')
while 1:
lines = f.readlines()
if not lines:
break
for line in lines:
print line
if (line[:5] == "anim "):
print 'next() '
ne = f.next()
print ' ne ',ne,'\n'
break
f.close()
Running this on a file does not show 'ne '.
The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.
readline() returns the next line of the file which contains a newline character in the end. Also, if the end of the file is reached, it will return an empty string.
To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.
Python readline() method reads only one complete line from the file given. It appends a newline (“\n”) at the end of the line. If you open the file in normal read mode, readline() will return you the string. If you open the file in binary mode, readline() will return you binary object.
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"
with open(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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With