Creating a new file, filename contains loop variable, python

前端 未结 5 1160
庸人自扰
庸人自扰 2020-11-27 17:10

I want to run a function over a loop and I want to store the outputs in different files, such that the filename contains the loop variable. Here is an example



        
5条回答
  •  时光取名叫无心
    2020-11-27 17:36

    Use f = open("file_{0}.dat".format(i),'w'). Actually, you might want to use something like f = open("file_{0:02d}.dat".format(i),'w'), which will zero-pad the name to keep it at two digits (so you get "file_01" instead of "file_1", which can be nice for sorting later). See the documentation.

提交回复
热议问题