如何将多个字符串替换并写入文件?

时间:2017-04-01 03:51:34

标签: python

我将数据从原始文件复制到新文件,然后将新值随机分配给我想要更改的字符串。出于某种原因,我所拥有的代码只会替换我的一个字符串。我尝试过编写与四个f.write命令相对应的四个不同的filedata.replace行,但这不会起作用。我也曾试图在一个命令中提供filedata.replace多个参数,但这也会产生问题。

import numpy as np
import random
import math
import shutil

for i in range (1,5):
    shutil.copy('template.par', 'a.par')

    a = str(random.uniform(0.00000000000000, 0.0001))                #sigma0
    b = str(random.uniform(0.00000000000000, 1))                     #sigmaslope
    c = str(random.uniform(0.05000000000000, 0.1))                   #viscosity
    d = str(random.uniform(0.00000000000000, 0.00001))                #aspectratio

    f = open('a.par','r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace("6.3661977237e-4", a)
    newdata = filedata.replace("0.0", b)
    newdata = filedata.replace("0.05", c)
    newdata = filedata.replace("1e-5", d)

    f = open('a.par','w')
    f.write(newdata) 
    f.close()

1 个答案:

答案 0 :(得分:1)

Bug在以下部分:

statName

最后一行始终会使用newdata = filedata.replace("6.3661977237e-4", a) newdata = filedata.replace("0.0", b) newdata = filedata.replace("0.05", c) newdata = filedata.replace("1e-5", d) 覆盖newdata。因此,之前的所有filedata都没有用。

您可以将filedata.replace()替换为filedata

来解决此问题
newdata

如果这不能解决您的问题,请告诉我。