如何更改文本文件中的特定值?

时间:2017-11-03 14:44:55

标签: python-3.x

我有两个数据文件(Amin文件和卷文件)。形成第一个想要找出字符串“Amin”前面的数字。然后我想打开第二个文件并检查所有卷号,如果它们小于Amin,则将该特定号码更改为Amin。

Amin文件如下所示:

 GP_DEF  1 4 "Zeitintervall Q_Strg [s]" 2 9.00000000e+002 0.00000000e+000  1
 GP_DEF  1 5 "Hmin [m]" 2 1.00000000e-002 0.00000000e+000 1.79769313e+308
 GP_DEF  1 6 "VELMAX [m/s]" 2 1.50000000e+001 0.00000000e+000 1
 GP_DEF  1 7 "Amin" 2 0.5 0.5 0.5

卷文件如下所示:

SCALAR
ND     6813
ST  0
TS      0.0
    0.207
    0.313
    0.423
    0.595
    0.930
    0.714
    0.590
    0.1
    1.652

结果应如下所示:

SCALAR
ND     6813
ST  0
TS      0.0
    0.5
    0.5
    0.5
    0.595
    0.930
    0.714
    0.590
    0.5 
    1.652

我编写的代码不是以pythonic方式编写的,但逻辑上应该可以工作。但它不会产生结果。我的代码如下:

with open("VOLUMEN.dat") as f1, open('V_korr.dat', 'w') as out:
    mylist = f1.read().splitlines()[0:4]
    print(mylist)
    for item in mylist:
        out.write("%s\n" % item)

with open('hydro_as-2d.2dm', 'r') as f, open('Amin.txt', 'a') as outfile:
    for line in f:
        if line.startswith('GP_DEF  1 7 "Amin" '):
            try:
                line = line.strip()
                columns = line.split()
                Amin = float(columns[4])
                print("{:.2f}".format(Amin), file=outfile)
            except ValueError:
                pass

with open("VOLUMEN.dat") as f1, open('V_korr.dat', 'w') as out:
    for line in f1:
        if line.startswith('GP_DEF  1 7 "Amin" '):
            try:
                line = line.strip()
                columns = line.split()
                Vol = float(columns[0])
                if (V<Amin):
                    print("{:.2f}".format(Amin), file=outfile)
                else :
                    print(line,file=outfile)                                
            except ValueError:
                pass

请提示,我在哪里犯了错误?谢谢!

1 个答案:

答案 0 :(得分:2)

我不会尝试解开你的代码,而是试着尝试解决你有些不明确的问题。这是我的建议:

#! /usr/bin/env python
#


def find_amin(fname, pattern, idx=5, default=None):
    """Locate first matching line in fname and return field at offset idx

    If pattern is not found return default value.
    """
    with open(fname) as fd:
       for line in fd:
          if line.startswith(pattern):
             return line.split()[idx]
       else:
          return default


def adjust_volume_file(fname, limit, skip=3, indent=3):
   """Return lines in fname as a list adjusting data smaller than limit

   Do not change the first skip lines.  Adjusted numbers are output
   with a margin of indent spaces.
   """
   margin = indent * " "
   result = []
   with open(fname) as fd:
      for idx, line in enumerate(fd):
         if idx > skip:
            result.append(margin + str(max(float(line), limit)) + '\n')
         else:
            result.append(line)
   return result


if __name__ == "__main__":
    amin = float(find_amin('amin-file.txt', ' GP_DEF  1 7 "Amin"'))

    adjusted_data = adjust_volume_file('VOLUMEN.dat', amin)

    with open('V_korr.dat', 'w') as fd:
        fd.writelines(adjusted_data)