2017-04-01 90 views
0

我正在將數據從原始數據複製到新文件,並隨機分配新值給我想要更改的字符串。出於某種原因,我擁有的代碼只會替換我的一個字符串。我試着寫了四個不同的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() 
+0

忽略我在範圍內的行。 – dlsj

+0

在每個'newdata = ...'行之間添加2行。 'print(newdata)','print(filedata)' – fdsa

+0

@fdsa這仍然只取代一行。 – dlsj

回答

1

bug在部分:

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) 

最後一行將始終與filedata覆蓋newdata。所以,以前的所有filedata.replace()都是沒用的。

您可以通過newdata更換filedata修復:

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

讓我知道這並不解決您的問題。

+0

它工作了!非常感謝你。 – dlsj

+0

你可能想接受這個答案! :) –

+0

這種新的,道歉,但認爲它完成! – dlsj

相關問題