python download不带文件名的文件/文件流

本文介绍了一种从特定URL下载ZIP格式文件的方法,并详细解释了如何使用Python的requests库来实现文件流下载,同时涵盖了文件解压及删除操作。

需求:需要下载文件/文件流,文件为zip的压缩包,url不现实任何文件格式

  • 下载文件
    def download_file():
        filepath = './data/'
        file_name = '{}{}.zip'.format(filepath, self.day)

        url = 'https://xx.com/download.do?custId=1103383695&taskId=10002779'
        header = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cookie': COOKICE,
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'
        }

        req = requests.get(url=url, headers=header)
        with open(file_name, 'wb') as f:
            f.write(req.content)

		# 解压缩
        import zipfile
        with zipfile.ZipFile(file_name) as zf:
            zf.extractall(path=filepath)

        import os
        os.remove(file_name)
  • 下载文件流
    def download_file(url, method='get'):
        filepath = './data/'
        file_name = '{}{}.zip'.format(filepath, self.day)

        paras = {
    'access_token': token,
    'selectDate': yestoday
}

        if method == 'get':
            req = requests.get(url=url, params=paras, stream=True)
        else:
            req = requests.post(url=url, json=paras, stream=True)
  

        with open(file_name, 'wb') as f:
            for chunk in req.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)

		# 解压缩
        import zipfile
        try:
	        with zipfile.ZipFile(file_name) as zf:
    	        zf.extractall(path=filepath)
		
	        import os
	        os.remove(file_name)
	        
		except:
			print('the file is not a correct zip file')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值