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