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.?