写入多个文件

时间:2016-10-06 01:17:54

标签: python file-io

我确信我们很多人都熟悉将数据写入outfile的python文件IO模式,如下所示;

outfile = open("myFile", "w")
data.dump()
outfile.close()

这就是假设我们已经拥有该文件并且可以访问它。现在,我想创造一些更复杂的东西。

假设我有一个迭代整数i的for循环。假设范围是1 - 1000,为了节省空间和头痛,我想写每次i%100 == 0时我已经在循环中保存的数据。这应该写十个文件:

for i in range (1, 1001):
    #scrape data from API and store in some structure
    ...
    if i % 100 == 0:
        #Create a new outfile, open it, and write the data to it
        ?...

我如何在python中自动创建具有唯一名称的新文件,并打开和关闭它们以写入数据?

1 个答案:

答案 0 :(得分:1)

>>> my_list = []
>>> for i in range(1, 1001):
...     # do something with the data... in this case, simply appending i to a list
...     my_list.append(i)
...     if i % 100 == 0:
...         # create a new file name... it's that easy!
...         file = fname + str(i) + ".txt"
...         # create the new file with "w+" as open it
...         with open(file, "w+") as f:
...             for item in my_list:
...                 # write each element in my_list to file
...                 f.write("%s" % str(item))
...         print(file)
... 
file100.txt
file200.txt
file300.txt
file400.txt
file500.txt
file600.txt
file700.txt
file800.txt
file900.txt
file1000.txt

填写空格,但是简单的字符串连接可以解决这个问题。