#!/usr/bin/python

import datetime
import os
import re

# Path to directory containing DL .dat files
base_path = '/1/home/welch/DLplots'

# Position string containing values for your location
posn_strg = '# Position (lat, lon, elev(m)): 43.2687, -79.9596, 70\n'

files =  [f for f in os.listdir(base_path) if re.match(r'20[1-2][0-9][01][0-9][0-3][0-9]_[0-2][0-9][0-5][0-9][0-5][0-9]_\.dat', f)]

for file in files:
   with open(file) as f:
       # Print old file name
       print file
       # Determine new file name and print it out
       out_f = file.replace('_.dat','_pos.dat')
       print out_f
       # Read lines from old file
       lines = f.readlines()
       # Open new file
       with open(out_f,"w") as o_f:
          # Loop through each line in old file
          for line in lines:
             # Check for header line containing "# Position"
             if ('# Position' not in line):
                # If we've reached here, this is not a header line containing "# Position" so just write it out to new file
                o_f.write(line)
             else:
                # If we've reached here, this is a header line containing "# Position"!
                # Determine the length of the line
                lenpos = len(line)
                # If the length is 33 or 34, it doesn't contain actual values, so write out the values for your location 
                if (lenpos == 33 or lenpos == 34):
                   o_f.write(posn_strg)
                else:
                   # If the length is longer, assume that the values are already there and write the line out to the new file
                   o_f.write(line)
       # Close the new file
       o_f.close()
   # Close the old file
   f.close()
