python中如何自动命名文件?

How to do auto file naming in python?

有一个名为 'links' 的列表,我想在这个列表中写入与 link 数量一样多的文件(我正在做网络抓取)。例如,如果列表包含 100 links,我想将每个 link 的数据写入单独的文本文件,如 '1.txt','2.txt',' 3.txt'…….

如何在 python 中实现这种类型的自动文件命名?

您可以使用 for 循环..

for i in range(1, 101): # since you started at 1 in your question
    fname='{}.txt'.format(i)
    with open(fname, 'wb') as f:
        f.write(data) # write your data to the file..
        f.close()
for l, link in enumerate(links):
    filename = str(l+1)+".txt"
    #open file and write link contents to it

enumerate 为您提供列表中的索引、值对,您可以只使用索引号作为文件名