I am reading in a file and wonder if there's a way to read the next line in a for loop?
I am currently reading the file like this:
file = open(input,"r").read()
for line in file.splitlines():
line = doSomething()
So is there anyway I can retrieve the next line of the file in that for loop such that I can perform some operation in the doSomething()
function?
Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.
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.
There are many ways in which you can skip a line in python. Some methods are: if, continue, break, pass, readlines(), and slicing.
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-in file
type object in python. I named it infile
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))
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