侧边栏壁纸
博主头像
小白博主等级

just do it!

  • 累计撰写 60 篇文章
  • 累计创建 77 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Python练习小程序-文件读取、写入、下载、压缩

小白
2021-10-31 / 0 评论 / 0 点赞 / 97 阅读 / 293 字

读取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()
0

评论区