read value from the next line of a match

时间:2016-04-07 10:48:23

标签: python

I am trying to get the lattice parameter from a file, like sysname:

lattice parameter A  [a.u.] 
    8.069100000000

And I have to grab the number from the next line of the match. I have written the script as:

   with open(sysname, "r") as sysinp:
        for line in sysinp:
            if line.startswith("lattice parameter A"):
                next(sysinp)
                print(line.strip())

I was expecting next() to go to the next line, which is not happening unfortunately. print() is printing the matching line.

What I am doing wring here?

3 个答案:

答案 0 :(得分:2)

你已经获得了下一行,但是你还没有分配任何东西。您需要使用line = next(sysinp)而不是next(sysinp)。您也可以使用print(next(sysinp).strip())代替。

答案 1 :(得分:1)

This should help:

line = next(sysinp)

In your code you don't use the line read by next() but still use the previous line from the for loop, i.e. the matching line.

The whole code snippet:

with open(sysname, "r") as sysinp:
    for line in sysinp:
        if line.startswith("lattice parameter A"):
            line = next(sysinp)
            print(line.strip())

答案 2 :(得分:0)

您需要捕获下一行:

with open(sysname, "r") as sysinp:
    for line in sysinp:
        if line.startswith("lattice parameter A"):
            try:
                line = next(sysinp)
                print(line.strip())
            except StopIteration:
                # handle the case where there is no next line