boto3的IO错误download_file [英] IO Error in boto3 download_file

查看:111
本文介绍了boto3的IO错误download_file的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我正在使用boto3代码从s3下载文件.这是以下代码.

I am using boto3 code to download file from s3.Here is the following code.

for record in event['Records']:
    bucket = record['s3']['bucket']['name']
    key = record['s3']['object']['key']
    print (key)
    if key.find('/') < 0 :
    if len(key) > 4 and key[-5:].lower() == '.json': //File is uploaded outside any folder

        download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)
    else:
        download_path = '/tmp/{}/{}'.format(uuid.uuid4(), key)//File is uploaded inside a folder

如果在s3存储桶中上传了新文件,则会触发此代码,并使用此代码下载新上传的文件.

If a new file is uploaded in s3 bucket,this code is triggered and that newly uploaded file is downloaded by this code.

在任何文件夹之外上传时,此代码都可以正常工作.

This code works fine,when uploaded outside any folder.

但是,当我在目录中上载文件时,发生IO错误. 这是我遇到的IO错误的转储.

However,when i upload a file inside a directory,IO error happens. Here is a dump of the IO error i am encountering.

[Errno 2]没有这样的文件或目录: /tmp/316bbe85-fa21-463b-b965-9c12b0327f5d/test1/customer1.json.586ea9b8 : IOError

[Errno 2] No such file or directory: /tmp/316bbe85-fa21-463b-b965-9c12b0327f5d/test1/customer1.json.586ea9b8: IOError

test1是我的s3存储桶中的目录,其中上载了customer1.json.

test1 is the directory inside my s3 bucket,where customer1.json is uploaded.

查询

关于如何解决此错误的任何想法?

Any thoughts on ,how to resolve this error?

推荐答案

出现错误,因为您试图将文件下载并保存到不存在的目录中.在下载文件之前,使用 os.mkdir 创建目录.

Error raised because you attempted to download and save file into directory which not exists. Use os.mkdir prior downloading file to create an directory.

# ...
else:
    item_uuid = str(uuid.uuid4())
    os.mkdir('/tmp/{}'.format(item_uuid))
    download_path = '/tmp/{}/{}'.format(item_uuid, key)  # File is uploaded inside a folder

注意:最好使用

Note: It's better to use os.path.join() while operating with systems paths. So code above could be rewritten to:

# ...
else:
    item_uuid = str(uuid.uuid4())
    os.mkdir(os.path.join(['tmp', item_uuid]))
    download_path = os.path.join(['tmp', item_uuid, key]))

也可能会引发错误,因为您在s3存储桶文件的下载路径中包括了"/tmp/",而不包括tmp文件夹,因为它可能在s3上不存在.使用这些文章,确保您的方法正确:

Also error may be raises because you including '/tmp/' in download path for s3 bucket file, do not include tmp folder as likely it's not exists on s3. Ensure you are on the right way by using that articles:

Python s3示例

这篇关于boto3的IO错误download_file的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆