为循环文件下载器添加唯一的文件名

时间:2019-01-31 19:30:54

标签: python for-loop

我正在使用for循环从API请求文件。我想使用名称列表(image_list)来命名每个文件。

for i in download_url_list:
response = requests.get(i, stream=True)
with open('/Users/Zack/Downloads/' + ??? +  '.zip', "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

enter image description here

2 个答案:

答案 0 :(得分:0)

可以使用其改变在每次迭代的变量;

查看此内容:-

>>> list1 = [ 'a', 'b', 'c', 'd' ]
>>> 
>>> var, list2 = 0, []
>>> for i in list1:
...     filename = 'file{}'.format(var)
...     var += 1
...     list2.append(filename)
... 
>>> list2
['file0', 'file1', 'file2', 'file3']

答案 1 :(得分:0)

您可以在URL和文件名之间创建映射(字典),然后遍历字典。

另一种方法是zip两个列表并遍历结果。

还有一种方法是基于索引来枚举网址,并得到一个文件名。

在第一选项假定没有重复在download_url_lists 最后两个假设download_url_listsimage_list的大小相同。

info = zip(download_url_lists, image_list)
for url, filename in info:
    ...

# or
mapping = dict(info)
for url, filename in mapping.iteritems():
    ...

# or 
for index, url in enumerate(download_url_lists):
    filename = image_list[index]
    ...