How to writing files using Python For-loop

141 Views Asked by At

I am new to SO and self-learning Python. I am using Pymatgen to study computational material science and I have a question which I have been struggling with and couldn't find an answer anywhere. I have a list - output from the script like the picture.

I would like to use a for-loop to write to different files for visualization. I have been writing the output manually like the script below and hoping to use a for-loop to simplify the script and make it look better.

p1 = add_h2o[0]
p1.to(filename = 'Al2O3_0001_9_H2O_P_1.POSCAR.vasp')
p2 = add_h2o[1]
p2.to(filename = 'Al2O3_0001_9_H2O_P_2.POSCAR.vasp')
p3 = add_h2o[2]
p3.to(filename = 'Al2O3_0001_9_H2O_P_3.POSCAR.vasp')
p4 = add_h2o[3]
p4.to(filename = 'Al2O3_0001_9_H2O_P_4.POSCAR.vasp')
p5 = add_h2o[4]
p5.to(filename = 'Al2O3_0001_9_H2O_P_5.POSCAR.vasp')
p6 = add_h2o[5]
p6.to(filename = 'Al2O3_0001_9_H2O_P_6.POSCAR.vasp')
p7 = add_h2o[6]
p7.to(filename = 'Al2O3_0001_9_H2O_P_7.POSCAR.vasp')
p8 = add_h2o[7]
p8.to(filename = 'Al2O3_0001_9_H2O_P_8.POSCAR.vasp')
p9 = add_h2o[8]
p9.to(filename = 'Al2O3_0001_9_H2O_P_9.POSCAR.vasp')
p10 = add_h2o[9]
p10.to(filename = 'Al2O3_0001_9_H2O_P_10.POSCAR.vasp')
p11 = add_h2o[10]
p11.to(filename = 'Al2O3_0001_9_H2O_P_11.POSCAR.vasp')
1

There are 1 best solutions below

0
On

From the code that you provided, it can seen that you are saving add_h2o[0] through add_h2o[10] in files.

You are saving add_h2o[0] in a file Al2O3_0001_9_H2O_P_1.POSCAR.vasp, and add_h2o[1] in a file Al2O3_0001_9_H2O_P_2.POSCAR.vasp, ...

Do you notice any patterns?

The number of the file is always 1 greater than the index of the element in array which you are trying to save. Thus we can run a loop from 0 to 10 and for each number i in the loop, the number of the file would be i + 1. Hence, the code is as follows.

for i in range(11):
  add_h2o[i].to(filename='Al2O3_0001_9_H2O_P_{}.POSCAR.vasp'.format(i + 1))

Does this solve your issue?