我有一个名为 myfile.txt 的文件,如下所示:
&cntrl
pTopt = 298.15, pdens = 0.997, prcut = 12.0, pion = t,
pihot = t, prQM = 5.5, prSM = 5.3, prQI=3.0, piguess = f,
pinit = t, pnstep = 5000, pnscale = 100,
pnstat = 5, pnout = 5, pnrst = 5, pioutc = t, pioutv = t, pnoutc=5,
pnoutv = 5,
msolute = t, nosa = 1, pichrg = t
gfileOut = 'as-1.out',
gfileEnout = 'as-1.en',
gfileInfo = 'as-1.info',
gfileStart = 'init.in',
gfileRst = 'as-1.rst',
gfileTraj = 'as-1.traj',
gfileVeloc = 'as-1.vel',
gfileQmen = 'as-1.qmen'
&end
使用上面给出的单个文件我想要创建10个文件,但我想以每个新文件中变量值随文件更改次数的变化的方式操作最后8个变量的值,即10个文件是然后创建最后八个变量的值,如tength文件中的gfileOut,应为'as-10.out'。 为此,我有一个代码如下:
#!/usr/bin/python3
for i in range(10):
f = open('file' +str(i)+'.txt','w')
f.write("&cntrl pTopt = 298.15, pdens = 0.997, prcut = 12.0,pion=t,"+"\n"+
"pihot = t, prQM = 5.5, prSM = 5.3, prQI=3.0, piguess = f,"+"\n"+
"pinit = t, pnstep = 5000, pnscale = 100,"+"\n"+"pnstat = 5, pnout = 5,
pnrst = 5, pioutc = t, pioutv = t, pnoutc = 5, pnoutv = 5,"+"\n"+
"msolute = t, nosa = 1, pichrg = t"+"\n"+'gfileOut = as-' +str(i)+ ".out,"+"\n"+
'gfileEnout = as-' +str(i)+ '.en,'+"\n"+'gfileInfo = as-' +str(i)+".info,"+"\n"+
'gfileStart = init' +str(i)+ ".in,"+"\n"+'gfileRst = as' +str(i)+ ".rst,"+"\n"+
'gfileTraj = as' +str(i)+ ".traj,"+"\n"
+'gfileVeloc = as' +str(i)+ ".vel,"+"\n"+'gfileQmen = as' +str(i)+ '.qmen'+"\n"+"&end ")
f.close()
上面给出的代码产生了正确的输出,但我想要一种方法来读取myfile.txt并更改上面提到的最后八个变量的值,然后使用该文件创建十个新文件。
答案 0 :(得分:1)
str.format处理要写入每个文件的字符串中的插入。
# Write the files.
for i in range(1, 11):
with open('file' +str(i)+ '.txt','w') as f:
f.write(
('&cntrl pTopt = 298.15, pdens = 0.997, prcut = 12.0, pion=t,\n'
'pihot = t, prQM = 5.5, prSM = 5.3, prQI=3.0, piguess = f,\n'
'pinit = t, pnstep = 5000, pnscale = 100,\n'
'pnstat = 5, pnout = 5, pnrst = 5, pioutc = t, pioutv = t, pnoutc = 5, pnoutv = 5,\n'
'msolute = t, nosa = 1, pichrg = t\n'
'gfileOut = as-{index}.out,\n'
'gfileEnout = as-{index}.en,\n'
'gfileInfo = as-{index}.info,\n'
'gfileStart = init{index}.in,\n'
'gfileRst = as{index}.rst,\n'
'gfileTraj = as{index}.traj,\n'
'gfileVeloc = as{index}.vel,\n'
'gfileQmen = as{index}.qmen\n'
'&end ').format(index=i))
注意:该字符串包含{index}
,它由范围为(1,10)的i的值替换。
编辑:由于误解了第1条评论提醒的问题的详细信息而重新发帖。遗憾。
编辑:看着需要从文件中读取,所以这可能有所帮助。
template.txt:
&cntrl pTopt = 298.15, pdens = 0.997, prcut = 12.0, pion=t,
pihot = t, prQM = 5.5, prSM = 5.3, prQI=3.0, piguess = f,
pinit = t, pnstep = 5000, pnscale = 100,
pnstat = 5, pnout = 5, pnrst = 5, pioutc = t, pioutv = t, pnoutc = 5, pnoutv = 5,
msolute = t, nosa = 1, pichrg = t
gfileOut = as-{index}.out,
gfileEnout = as-{index}.en,
gfileInfo = as-{index}.info,
gfileStart = init{index}.in,
gfileRst = as{index}.rst,
gfileTraj = as{index}.traj,
gfileVeloc = as{index}.vel,
gfileQmen = as{index}.qmen
&end
主脚本:
# Read template file.
with open('template.txt') as r:
content = r.read()
# Write the files.
for i in range(1, 11):
with open('file' +str(i)+ '.txt','w') as f:
f.write(content.format(index=i))