Python,文本文件中的Catch值

问题描述 投票:0回答:2

我有一个文件(fluiddynamic代码的输出),我想在dilute dimensional Zimm longest开头的行之后写入值

这里有兴趣报道:

 dilute dimensional Zimm longest relaxation time, dil_chtime=
    3.29486769328041

到目前为止我刚刚写了这一行:但我不知道为什么它没有抓住价值3.2948676932 ....

 zimm = 0.
  with open('memo.dat','r') as f:
        for line in f.readlines() :
            if(line.startswith(' dilute dimensional Zimm longest')):
                print (line)
                zimm = f.readline() # I suppose that this read the next line
             else:
                pass

这个框架的输出是:dilute dimensional Zimm longest relaxation time, dil_chtime=我怎样才能得到这个值?

python get
2个回答
1
投票

您可以使用next(f)获取下一行

例如:

with open('memo.dat') as f:
    for line in f:     #Iterate Each Line
        if line.strip().startswith('dilute dimensional Zimm longest'): #Check Condition
            print(next(f))     #Get Value
            break

1
投票

memo.dat:

dilute dimensional Zimm longest relaxation time, dil_chtime=

    3.29486769328041

Python 2.x:

zimm = 0.
nextLine = False     # a boolean flag to get the next line
with open('memo.dat', 'r') as f:
    content = f.readlines()    
    # you may also want to remove empty lines
    content = [l.strip() for l in content if l.strip()]
    for line in content:
        try:
            if (line.startswith('dilute dimensional Zimm longest')):
                nextLine = not nextLine
            elif nextLine:
                print(line)
                nextLine = not nextLine
        except StopIteration:
            pass

OUTPUT:

3.29486769328041

Python例如:

使用next()

if (line.startswith('dilute dimensional Zimm longest')):
    print(next(f))
© www.soinside.com 2019 - 2024. All rights reserved.