Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next line in a file

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?

like image 845
overloading Avatar asked Sep 28 '12 20:09

overloading


People also ask

Which method of file objects will return the next line?

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.

How do you write a string to a file on a new line every time in Python?

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.

How do you start a new line in a text file in Python?

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.

How do you skip a line in Python?

There are many ways in which you can skip a line in python. Some methods are: if, continue, break, pass, readlines(), and slicing.


1 Answers

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:

  1. Don't call your variable file; it masks the built-in file type object in python. I named it infile instead.

  2. 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))
    
like image 114
Martijn Pieters Avatar answered Sep 28 '22 03:09

Martijn Pieters