Google云存储+Python:有没有办法在GCS的某个文件夹中列出obj?

2024-03-29 02:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我将编写一个Python程序来检查一个文件是否在Google云存储的某个文件夹中,基本思想是获取文件夹中所有对象的list,一个文件名list,然后检查文件abc.txt是否在文件名list

现在的问题是,看起来Google只提供了一种获取objlist的方法,即uri.get_bucket(),请参见下面的代码,它来自https://developers.google.com/storage/docs/gspythonlibrary#listing-objects

uri = boto.storage_uri(DOGS_BUCKET, GOOGLE_STORAGE)
for obj in uri.get_bucket():
    print '%s://%s/%s' % (uri.scheme, uri.bucket_name, obj.name)
    print '  "%s"' % obj.get_contents_as_string()

uri.get_bucket()的缺点是,它看起来是先获取所有对象,这是我不想要的,我只需要获取特定文件夹(例如gs//mybucket/abc/myfolder)的obj名称list,这应该很快。

有人能帮忙回答吗?感谢每一个回答!


Tags: 文件对象name程序文件夹objgetbucket
3条回答

更新:下面是针对Python的旧“Google API客户端库”的,但如果不使用该客户端,则更喜欢针对Python的新“Google Cloud客户端库”(https://googleapis.dev/python/storage/latest/index.html)。对于较新的库,等效于以下代码:

from google.cloud import storage

client = storage.Client()
for blob in client.list_blobs('bucketname', prefix='abc/myfolder'):
  print(str(blob))

下面是老客户的答案。

您可能会发现使用JSON API更容易,它有一个功能齐全的Python客户端。它有一个函数,用于列出带有前缀参数的对象,您可以使用该参数以这种方式检查某个目录及其子目录:

from apiclient import discovery

# Auth goes here if necessary. Create authorized http object...
client = discovery.build('storage', 'v1') # add http=whatever param if auth
request = client.objects().list(
    bucket="mybucket",
    prefix="abc/myfolder")
while request is not None:
  response = request.execute()
  print json.dumps(response, indent=2)
  request = request.list_next(request, response)

列表调用的完整文档如下:https://developers.google.com/storage/docs/json_api/v1/objects/list

Google Python API客户端的文档如下: https://code.google.com/p/google-api-python-client/

您可能还需要查看gcloud-pythondocumentation

from gcloud import storage
connection = storage.get_connection(project_name, email, private_key_path)
bucket = connection.get_bucket('my-bucket')

for key in bucket:
  if key.name == 'abc.txt':
    print 'Found it!'
    break

但是,最好检查文件是否存在:

if 'abc.txt' in bucket:
  print 'Found it!'

这对我有效:

client = storage.Client()
BUCKET_NAME = 'DEMO_BUCKET'
bucket = client.get_bucket(BUCKET_NAME)

blobs = bucket.list_blobs()

for blob in blobs:
    print(blob.name)

list_blobs()方法将返回一个迭代器,用于查找bucket中的blob。 现在可以遍历blob并访问bucket中的每个对象。在本例中,我只是打印出对象的名称。

这些文档帮助我:

我希望我能帮忙!

相关问题 更多 >