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()
目标是根据文件中的关键字选择第一个非空格值,并将其附加索引。然后使用索引将其替换为具有新值的同一文件。我成功地选择了文件中的现有值,但可以相应地替换新值并将其保存在相同的文件名中。这是代码,我试过。 任何人都可以建议修改它们或建议一个简单明了的更好的代码。?
答案 0 :(得分:1)
老实说,我没有理解你100%的目标,但我想提出一个更适合你需求的清洁解决方案。主要思想是获取旧文件的每一行,相应地替换值,将结果行存储在列表中,最后将这些行列表存储在新文件中。
# 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