0

I have been trying to modify a specific word in a text file, using a for loop. The word I wish to change in the Fe.in file is >latt_par. I would like to create one file for each value of vol in the list. However, I just keep getting the last one "3.05". Is there a way you can guide me please? I am starting in Python.

Here is my code

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()

I would also like to replace another string in the file Fe.in, which I want to run over the variable temp, but I have not been able to. Any help is greatly appreciated!

1 Answers1

0
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)

Like that you don't need to open your template N times, and the with method allows to not close the file with no troubles.

Synthase
  • 5,849
  • 2
  • 12
  • 34