-2

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')
beliz
  • 402
  • 1
  • 5
  • 25
  • Does this answer your question? [Writing to a file in a for loop](https://stackoverflow.com/questions/11198718/writing-to-a-file-in-a-for-loop) – EnriqueBet Mar 24 '20 at 20:29
  • Welcome to Stackoverflow, please read [How To Ask](https://stackoverflow.com/help/how-to-ask). Pay special attention to [How To Create MCVE](https://stackoverflow.com/help/mcve). Make sure you tag your question with proper labels (programming language, relevant technologies etc). The more effort you'll put into posting a good question: one which is easy to read, understand and which is [on topic](https://stackoverflow.com/help/on-topic) - the chances are higher that it will attract the relevant people and you'll get help even faster. Good luck! – Nir Alfasi Mar 24 '20 at 20:29

1 Answers1

1

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?