【问题标题】:Getting data from the url using python and unzipped使用python从url获取数据并解压
【发布时间】:2021-05-31 12:08:05
【问题描述】:

问题:我想从以下 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'

【问题讨论】:

  • 这是linux环境吗?
  • 您正在开发什么操作系统?你确定路径data/1Q16 存在吗?我的意思是如果目录不存在,open不会创建目录,它只能在已经存在的目录中创建文件
  • @Take_Care_ 我认为它会像创建数据目录一样自动创建 1Q16!我正在使用 Windows。
  • @Simpson's Paradox 如果你想这样工作,最好检查pathlib 模块,它有更高级的东西。
  • @Take_Care_ 当我手动创建目录时它起作用了!我正在寻找自动的东西!

标签: python python-3.x pandas python-2.7


【解决方案1】:

问题是您的目录data/&lt;file&gt; 没有被创建,因此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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2014-10-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    相关资源
    最近更新 更多