2017-04-01 5 views
0

元のファイルから新しいファイルにデータをコピーしていて、変更したい文字列に新しい値をランダムに割り当てています。何らかの理由で、私が持っているコードは、私の文字列の1つだけを置き換えます。私は4つの異なるfiledata.replace行を4つのf.writeコマンドに対応させて書きましたが、うまくいかないでしょう。私もfiledata.replace複数の引数を1つのコマンドで与えることを試みたが、それも問題を作成します。複数の文字列をファイルに置き換えて書き込む方法は?

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

範囲線のfor iを無視します。 – dlsj

+0

それぞれの 'newdata = ...'行の間に2行を追加します。 'print(newdata)'、 'print(filedata)' – fdsa

+0

@fdsaこれはまだ1行だけを置き換えます。 – dlsj

答えて

1

バグはセクションにあります。

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) 

最終ラインは常にfiledatanewdataを上書きします。したがって、前のすべてのfiledata.replace()は役に立たなくなります。

あなたはnewdatafiledataを置き換えることによって、それを修正することができます:

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) 

は、このdoesntのはあなたの問題を解決するなら、私に教えてください。

+0

それは働いた!!!!どうもありがとうございました。 – dlsj

+0

これを答えとして受け入れることができます。 :) –

+0

これに新しいの一種、謝罪が、それが完了したと考えて! – dlsj

関連する問題