7

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

1
  • 1
    Well you're using return outside of a function, which is not allowed in Python. Wrap your code in a function like def getLine(...): and it's gonna be fine. Commented Sep 4, 2015 at 13:25

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.