我正在將數據從原始數據複製到新文件,並隨機分配新值給我想要更改的字符串。出於某種原因,我擁有的代碼只會替換我的一個字符串。我試着寫了四個不同的filedata.replace行,對應於四個f.write命令,但是這不行。我還試圖在一個命令中提供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()
忽略我在範圍內的行。 – dlsj
在每個'newdata = ...'行之間添加2行。 'print(newdata)','print(filedata)' – fdsa
@fdsa這仍然只取代一行。 – dlsj