Getting next line in a file
file = open(input,"r").read()
lines = file.read().splitlines()
for i in range(len(lines)):
line = lines[i]
next_line = lines[i+1]
Just loop over the open file:
infile = open(input,"r")
for line in infile:
line = doSomething(line, next(infile))
Because you now use the file as an iterator, you can call the next()
function on the infile
variable at any time to retrieve an extra line.
Two extra tips:
Don't call your variable
file
; it masks the built-infile
type object in python. I named itinfile
instead.You can use the open file as a context manager with the
with
statement. It'll close the file for you automatically when done:with open(input,"r") as infile: for line in infile: line = doSomething(line, next(infile))
I think that you mean that if you are in line n, you want to be able to access line n+1.
The simplest way to do that is to replace
for line in file.splitlines():
with
lines = file.readlines()
for i in xrange(len(lines)):
then you can get the current line with lines[i]
and the next line with lines[i+1]
the more pythonic way is to use enumerate
lines = file.readlines()
for index, line in enumerate(lines):
now you have the current line in "line" like normal, but you also have the index if you want to find a different line relative to it.