在 python 2.7 中列出 google 云存储中的文件

Listing files in google cloud storage in python 2.7

我在 Google API Engine 中有一个项目,我在其中使用 Google Cloud Storage 在一个任务中保存一些文件,并在另一个任务中列出其中的一些文件以进行处理.我在这里(this is in php, this in java and neither were very helpful, and 似乎是 python3)或外面找不到任何答案。 所以我想要的是这样的:

import cloudstorage

files = cloudstorage.list('/bucket/foo/bar')
for file in files:
  # process files

如果您确切知道所需的路径,可以使用来自云存储的 listbucket。因此,要列出“/bucket/foo/bar”中的所有文件,请使用:

import cloudstorage

files = cloudstorage.listbucket('/bucket/foo/bar')
for file in files:
  file_name = file.filename
  # process file

listbucket返回的迭代器中的每个文件都是GCSFileStat个实例

您还可以按文件名开头过滤文件,例如,列出以前文件夹中以 'baz':

开头的每个文件
files = cloudstorage.listbucket('/bucket/foo/bar/baz')

或者列出test.json之后的所有文件:

files = cloudstorage.listbucket('/bucket/foo/bar/test.json')

要在单元测试中使用这些,您需要从测试平台设置 blobstore 和 urlfect 存根:

import unittest
from google.appengine.ext import testbed

class CloudStorageTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.testbed = testbed.Testbed()
        cls.testbed.activate()

        cls.testbed.init_blobstore_stub()
        cls.testbed.init_urlfetch_stub()

在我的测试中,您需要 urlfetch 和 blobstore 存根才能在测试中使用云存储。 Here 是整个测试文件的要点