阿里云oss 批量检测文件是否存在

虽然阿里云oss的sdk提供了检测文件是否存在,但是在批量处理的时候你就会发现检测一次需要联网一次,如果文件过多最后会提示你链接数超过限制,最终无法进行检测了。

下面是阿里云提供的示例代码:

# -*- coding: utf-8 -*-
import oss2

# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('', '')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '')

exist = bucket.object_exists('')
# 返回值为true表示文件存在,false表示文件不存在。
if exist:
	print('object exist')
else:
	print('object not eixst')

那么其实可以反过来想,直接拉文件目录落下来进行比较,列举文件的代码如下:

# -*- coding: utf-8 -*-

# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('api-key', 'api-secret')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'https://oss-cn-beijing.aliyuncs.com', 'bucket-name')

file_arrary = []
# 设置Delimiter参数为正斜线(/)。
for obj in oss2.ObjectIterator(bucket, delimiter='/'):
    # 通过is_prefix方法判断obj是否为文件夹。s
    if obj.is_prefix():  # 文件夹
        #print('directory: ' + obj.key)
        for obj2 in oss2.ObjectIterator(bucket, prefix='%s' % obj.key):
            #print('file: ' + obj2.key)
            file_arrary.append(obj2.key)
    else:  # 文件
        file_arrary.append(obj.key)

如果要判断文件是否存在,只需要在数组中进行比较就可以了

file_arr = []
for file in file_arr:
    if file in file_arrary :
           print('esixts')
    else:
           print('not exists')

 

☆版权☆

* 网站名称:obaby@mars
* 网址:https://h4ck.org.cn/
* 个性:https://oba.by/
* 本文标题: 《阿里云oss 批量检测文件是否存在》
* 本文链接:https://h4ck.org.cn/2018/12/6300
* 短链接:https://oba.by/?p=6300
* 转载文章请标明文章来源,原文标题以及原文链接。请遵从 《署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5 CN) 》许可协议。


猜你喜欢:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注