【问题标题】:Listing files in google cloud storage in python 2.7在 python 2.7 中列出谷歌云存储中的文件
【发布时间】:2020-01-24 17:54:24
【问题描述】:

我在 Google API Engine 中有一个项目,我使用 Google Cloud Storage 在一项任务中保存一些文件,并在另一项任务中列出其中一些文件以处理它们。我在这里找不到任何答案(this 在 php 中,this 在 java 中,两者都不是很有帮助,this 似乎是 python3)或外部。 所以我想要的是这样的:

import cloudstorage

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

【问题讨论】:

    标签: python filesystems google-cloud-storage


    【解决方案1】:

    如果你确切地知道你想要的路径,你可以使用来自 cloudstorage 的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 是整个测试文件的要点

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 2012-12-24
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多