虽然阿里云oss的sdk提供了检测文件是否存在,但是在批量处理的时候你就会发现检测一次需要联网一次,如果文件过多最后会提示你链接数超过限制,最终无法进行检测了。
下面是阿里云提供的示例代码:
# -*- coding: utf-8 -*- import oss2 # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 auth = oss2.Auth('<youraccesskeyid>', '<youraccesskeysecret>') # Endpoint以杭州为例,其它Region请按实际情况填写。 bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourbucketname>') exist = bucket.object_exists('<yourobjectname>') # 返回值为true表示文件存在,false表示文件不存在。 if exist: print('object exist') else: print('object not eixst') </yourobjectname></yourbucketname></youraccesskeysecret></youraccesskeyid> |
那么其实可以反过来想,直接拉文件目录落下来进行比较,列举文件的代码如下:
# -*- 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
本文标题: 《阿里云oss 批量检测文件是否存在》