繁体   English   中英

使用 python 从 url 获取数据并解压缩

[英]Getting data from the url using python and unzipped

问题:我想从以下 url 中获取数据,但是,我收到了以下错误消息。 我想知道您是否可以指导我解决我的错误。 我很感激你的时间!

import requests
import os
urls = {'1Q16':'https://f001.backblazeb2.com/file/Backblaze-Hard-Drive-Data/data_Q1_2016.zip'}
if not os.path.isdir('data'):
    os.system('mkdir data')
    
for file in urls.keys():
    if not os.path.exists('data/' + file):
        os.system('mkdir ./data/' + file)
    
    print('Requesting response from: ' + urls[file])
    req = requests.get(urls[file])
    print('Writing response to: /data/' + file + '/' + file + '.zip')
    with open('data/' + file + '/' + file + '.zip', 'wb') as f:
        f.write(req.content)

    os.system('unzip ' + 'data/' + file + '/' + file + '.zip -d data/' + file + '/')
    print('Unzipping data...')
    
    os.system('rm ' + 'data/' + file + '/' + file + '.zip')
    print(file + ' complete.')
    print('------------------------------------------------------------------------------- \n')
        

错误信息

Requesting response from: https://f001.backblazeb2.com/file/Backblaze-Hard-Drive-Data/data_Q1_2016.zip
Writing response to: /data/1Q16/1Q16.zip
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-9-251ee1e9c629> in <module>
      9     req = requests.get(urls[file])
     10     print('Writing response to: /data/' + file + '/' + file + '.zip')
---> 11     with open('data/' + file + '/' + file + '.zip', 'wb') as f:
     12         f.write(req.content)
     13 

FileNotFoundError: [Errno 2] No such file or directory: 'data/1Q16/1Q16.zip'

问题是您的目录data/<file>没有被创建,因此open()无法打开文件,因为您提供的路径的一部分不存在。 为了确保在 python 上加入路径时完全兼容,可以使用os.path.join() 对你来说,这将是:

import requests
import os
urls = {'1Q16':'https://f001.backblazeb2.com/file/Backblaze-Hard-Drive-Data/data_Q1_2016.zip'}
if not os.path.isdir('data'):
    os.makedirs("data")
    
for file in urls.keys():
    if not os.path.exists('data/' + file):
        os.makedirs(os.path.join("data",file))
    
    print('Requesting response from: ' + urls[file])
    req = requests.get(urls[file])
    print('Writing response to: /data/' + file + '/' + file + '.zip')
    with open(os.path.join("data", file, file + '.zip', 'wb') as f:
        f.write(req.content)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM