Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read next line after a matching line in python

Tags:

python-3.4

I am trying to go to next line after a match in python. I have a file:

ratio of lattice parameters  b/a  c/a
    1.000000000000    1.000000000000
lattice parameters  a b c  [a.u.] 
    9.448629942895    9.448629942895    9.448629942895

So, when I have "lattice parameters" at the beginning of line, I will read the next line (e.g. 9.448629942895 9.448629942895 9.448629942895) I am doing:

#!/usr/bin/python3
import sys

inpf = str(sys.argv[1])
print (inpf)
with open(inpf, "r") as ifile:
    for line in ifile:
        if line.startswith("lattice parameters"):
            print(line.strip())
            next(ifile)
            return next(ifile)

as is in the accepted answer here. But, in my case, it is giving error:

python xband.py AlSi2S2.sys 
  File "xband.py", line 11
    return next(ifile)
SyntaxError: 'return' outside function

What I am doing wrong here? NB: I want to go to and read next line. I have no special fascination on "return" I am using Python 3.4.2

like image 769
BaRud Avatar asked Sep 04 '15 13:09

BaRud


People also ask

How do you read the next line 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 print the nth line in Python?

Print input DataFrame, df. Initialize a variable nth_row. Use iloc() method to get nth row. Print the returned DataFrame.


2 Answers

Try:

with open(inpf, "r") as ifile:
    for line in ifile:
        if line.startswith("lattice parameters"):
            print(next(ifile, '').strip())

next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

like image 143
Praveen Avatar answered Jan 04 '23 04:01

Praveen


You are using a return statement outside of a function. For the code to work you schould either get rid of the return next(ifile) line or make a function in your script and call it.

like image 38
Maximilian Kindshofer Avatar answered Jan 04 '23 05:01

Maximilian Kindshofer