Skip to main content
 首页 » 编程设计

python之动态文件创建(命名)

2025年05月04日8lori

是否可以在 python 中执行以下操作?

i=1 
    while True:  
      w = open("POSCAR_i","w") 
      i=i+1 
      if i<10: 
        break 

所以基本上,它应该通过 POSCAR_10 创建 POSCAR_1。

谢谢。

请您参考如下方法:

使用 for 循环更加 pythonic(并且更好):

for idx in range(1,11): 
    f = open("POSCAR_%d" % idx, "w") 
    f.close() 

您还可以使用 format() 方法,尽管 % 运算符在野外仍然更为常见,但现在正式首选该方法。