我目前有一个for循环,它将替换文本文件中的字符串,但我希望它们使用我已定义的变量替换这些字符串。
k_constant_vec = [.15707963267,.2221441469,.31415926535,.35124073655,.44428829381,.88857658763,1.33286488145];
for t in range(1, len(k_constant_vec)):
infile = open('/home/john/projects/simplecodes/textreplace/ex22.i')
outfile = open('/home/john/projects/simplecodes/textreplace/newex22-[t].i', 'w')
replacements = {'k_constant = k_constant_vec[t-1]':'k_constant = k_constant_vec[t]','file_base = out':'file_base = out-[t]'}
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
outfile.write(line)
infile.close()
outfile.close()
我基本上想要使用for循环来创建一堆新的.i文件。例如,这将创建7 .i文件,标记为newex22-1,newex22-2,等等,每个文件都有不同的k_constant = k_constant_vec[1]
,k_constant = k_constant_vec[2]
,其中替换了ect字符串。
由于
答案 0 :(得分:0)
您的代码存在一些小错误/样式问题。它还不清楚为什么你有虚弱。以下是我认为你想要做的更加pythonic的方式:
k_constant_vec = [.15707963267,.2221441469,.31415926535,.35124073655,.44428829381,.88857658763,1.33286488145];
file_prefix = '/home/john/projects/simplecodes/textreplace/newex22-[%s].i'
for index in range(len(k_constant_vec)):
with open(file_prefix % (index + 1), 'wb') as f:
f.write('k_constant = %s' % k_constant_vec[index])
答案 1 :(得分:0)
我实际解决了它,我会发布我在这里做的事情,以防有人搜索到类似的问题。我使用了乔治建议结合在for循环中使用%s和%。
k_constant_vec = [.15707963267,.2221441469,.31415926535,.35124073655,.44428829381,.88857658763,1.33286488145];
for t in range(0,len(k_constant_vec)):
infile = open('/home/john/projects/simplecodes/textreplace/ex22.i')
outfile = open('/home/john/projects/simplecodes/textreplace/newex22-'+repr(t)+'.i', 'w')
replacements = {'k_constant = .15707963267':'k_constant = %s' % k_constant_vec[t],'file_base = out':'file_base = out-'+repr(t)}
#use default k_constant from ex22.i file
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
outfile.write(line)
infile.close()
outfile.close()
使用infile的重点是保留文本文件的格式。