如何 create/save 函数循环内的文件?

How to create/save files within a loop in a function?

如何 save/create 在函数的循环中创建文件?在下面的示例中,我想要 运行 一个函数,它在每次迭代中打印一条消息并保存一个包含该消息的文件。但是,它打印消息但只保存最后一个文件 (10)。我想这看起来不太可取。重点是,我的真正功能是生成多个数据集的综合水流模型。如果有人想查看或使用每个时间步长的所有数据,我想通过将所有内容写入磁盘来避免内存堵塞。我宁愿失去 CPU 性能也不愿堵塞内存。

  def worldloop(message='hello world',no=10):
      import numpy as np
      fname_template='/home/blubb/Desktop/blaa{cap}'
      for i in range(no):
          cap=no
          np.save(fname_template.format(cap=cap) , message )
          print message

你每次迭代都设置cap = no,然后使用cap作为文件名,所以你每次都覆盖同一个文件。

删除cap = no并将np.save(fname_template.format(cap=cap) , message )更改为np.save(fname_template.format(cap=i) , message )

你弄错了 cap=no,其中 no == 10 只需将其更改为 cap=i 或使用 i:

def worldloop(message='hello world',no=10):
      import numpy as np
      fname_template='/home/blubb/Desktop/blaa{cap}'
      for i in range(no):
          np.save(fname_template.format(cap=i) , message )
          print message