读取csv文件中的数据,遍历每行数据,并下载文件到指定文件夹,最后下载完将文件夹打成压缩包
import urllib.request
import os
import zipfile
'''
下载CSV表格中的数据并打包成压缩包
'''
basePath = os.path.abspath(os.path.dirname(__file__))
dirPath = str.format('{}\\files', basePath)
if not os.path.exists(dirPath):
os.makedirs(dirPath, True)
print(str.format('文件下载根目录:{}', dirPath))
f = open('data.csv','r')
filesInfo = f.readlines()
print(str.format('文件读取成功,即将下载的文件数量:{}', len(filesInfo)))
zf = zipfile.ZipFile(str.format('{}\\file.zip', basePath), "w", zipfile.zlib.DEFLATED)
allFile = zipfile.ZipFile()
for i,v in enumerate(filesInfo):
try:
print(str.format('开始下载第{}个元素,信息:{}', i, v))
infos = v.split('","')
if len(infos)>2 and i!=0:
code, name, url = infos[0], infos[1], infos[2]
code = code.replace('"','')
name = name.replace('"','')
url = url.replace('"','')
filePath = str.format('{}\{}', dirPath, name)
print(str.format('code:{}, name:{}, url:{}, 下载路径:{}', code, name, url, filePath))
urllib.request.urlretrieve(url, filePath)
zf.write(filePath)
except:
print(str.format('下载第{}个文件失败, 信息:{}', i, v))
zf.close()
f.close()
评论区