Gopalpur
Gopalpur

Reputation: 121

replace an array of values in a file with new values

global file_platform
file_platform='karbarge.DAT'
Dir=30
Hs=4
Tp=12
dummy=[]
newval=[Dir, Hs, Tp]
def replace():    
    oldval=[]    
    line_no=[]
    search_chars=['WaveDir', 'WaveHs', 'WaveTp']
    with open(file_platform) as f_input:
        for line_number, line in enumerate(f_input, start=1):
            for search in search_chars:
                if search in line:
                    first_non_space = line.strip().split(' ')[0]
                    x=search_chars.index(search)
                    dummy.append((search, first_non_space, line_number, x))
                    print (search, first_non_space, line_number, x)

    i=0
    j=0
    for line in fileinput.input(file_platform, inplace=1):
        print (i)
        if i==eval(dummy[j][2]):
            line = line.replace(eval(dummy[j][1]),str(newval[dummy[j][3]]))
            j=j+1
        sys.stdout.write(line)
        i=i+1

    return
replace()

Aim is to select the first non-space value based on keywords in a file and append it with index. Then using index replacing it in the same file wit new values. I'm successful in picking the existing values in file, but could replace with new values accordingly and save it in the same filename. Here is the code, i tried. Could anyone suggest modifications in them or suggest a better code that is simple and clear.?

Upvotes: 1

Views: 178

Answers (1)

lucasnadalutti
lucasnadalutti

Reputation: 5948

I honestly didn't understand 100% of your goal, but I would like to propose a cleaner solution that might suit your needs. The main idea would be to get each line of the old file, replace the values accordingly, store the resulting lines in a list and finally storing this list of lines in a new file.

# This dict associates the old values to the values to which they should be changed
replacing_dict = {'WaveDir': Dir, 'WaveHs': Hs, 'WaveTp': Tp}

new_lines = []
with open(file_platform) as f_input:
    for line in f_input:
        first_non_space = line.strip().split(' ')[0]
        if first_non_space in replacing_dict:
            line.replace(first_non_space, replacing_dict[first_non_space])

        new_lines.append(line)

# Write new_lines into a file and, optionally, replace this new file for the old file

Upvotes: 1

Related Questions