How to change certain values ​​in a text file?

I have two data files (Amin file and volume file). form the first one to find out the number before the line "Amin." Then I want to open the second file and check all the volume numbers, and if they are less than Amin, change this number to Amin.

The Amin file is as follows:

 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

The volume file is as follows:

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

The result should look like this:

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

I wrote the code in a non-Putin way, but it should work logically. But this does not produce a result. My code is as follows:

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

Please give a hint, where did I make a mistake? Thank!

+4
source share
1 answer

, . :

#! /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)
+2

Source: https://habr.com/ru/post/1688687/


All Articles