How can I change specific values in a text file?

I have two data files (Amin file and Volume file). form the first one want to find out the number in front of a string "Amin". Then I want to open the second file and check all of the volume numbers and if they are smaller than Amin change that specific number to Amin.

Amin file looks like the following:

 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

Volume file looks like the following:

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 be like the following:

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 have written a code not in a pythonic way but logically should work. But it does not create a result. My code is as following:

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 do a mistake? Thanks!

Upvotes: 4

Views: 64

Answers (1)

FredrikHedman
FredrikHedman

Reputation: 1253

I'm not going to try to untangle your code, but rather try to give a tentative solution to your somewhat unclear problem. Here is my suggestion:

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

Upvotes: 2

Related Questions