Python替换文本文件循环中的字符串

2024-03-29 01:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用for循环修改文本文件中的特定单词。我希望在Fe.in文件中更改的单词是>;拿铁。我想为列表中vol的每个值创建一个文件。然而,我只得到最后一个“3.05”。有什么方法可以指引我吗?我从Python开始

这是我的密码

vols = [2.65, 2.85, 3.05] 
temp = [100,200,300]
for x in vols:
  f = open('Fe.in','r')
  filedata = f.read()
  f.close()
  newvol = filedata.replace("latt_par", str(x))
f = open('Fe_' + str(x) +'.in','w')
f.write(newvol)
f.close()

我还想替换文件Fe.in中的另一个字符串,我想在变量temp上运行该字符串,但我还不能。 非常感谢您的帮助


Tags: 文件字符串ingtforcloseopen单词
1条回答
网友
1楼 · 发布于 2024-03-29 01:41:12
with open('Fe.in','r') as msg:
    data = msg.read()

for x in vols:
    wdata = data.replace("latt_par", str(x))

    with open('Fe_' + str(x) +'.in','w') as out_msg:
        out_msg.write(wdata)

这样,您就不需要打开模板N次,with方法允许不关闭文件而不会出现任何问题

相关问题 更多 >