仅列出来自Google云存储的文件

2024-04-24 08:55:52 发布

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

在地面军事系统中,我有bucket XYZ,下面有文件夹JM,下面有文件。例如:

XYZ/JM/file1.tar.gz,XYZ/JM/file2.tar.gz,XYZ/JM/file3.tar.gz,XYZ/JM/file4.tar.gz etc.

使用下面的代码,我可以列出文件,但其显示完整路径如下:

JM/file1.tar.gz,JM/file2.tar.gz,JM/file3.tar.gz

代码

from google.cloud import storage
storage_client = storage.Client.from_service_account_json()

BucketName="XYZ"
bucket=storage_client.get_bucket(BucketName)


filename=list(bucket.list_blobs(prefix="jm/"))
for name in filename:
       print(name.name)

查询:我想列出JM文件夹下的文件。我不想在列表中显示JM,只需显示文件ex:file1.tar.gz,file2.tar.gz


Tags: 文件代码namefrom文件夹clientbucketstorage
1条回答
网友
1楼 · 发布于 2024-04-24 08:55:52

云存储中的所有内容都被视为一个对象(甚至是文件夹)。请注意,如documentation上所述:

To the service, the object gs://your-bucket/abc/def.txt is just an object that happens to have "/" characters in its name. There is no "abc" directory; just a single object with the given name.

这就是为什么在使用list_blobs() method时会收到完整的对象“路径”,它实际上是对象的真实名称

用于过滤blob的list_blobs() method函数的prefix参数应该足以列出要查找的特定对象

但之后,你需要考虑使用^ {A4}或类似的string splitting方法,通过与'/'字符分开,只得到你认为相关的BLUB名称的一部分。p>

编辑

我测试了以下各项,结果成功了:

from google.cloud import storage
storage_client = storage.Client.from_service_account_json()

BucketName="XYZ"
bucket=storage_client.get_bucket(BucketName)


filename=list(bucket.list_blobs(prefix="jm/"))
for name in filename:
    try:
        prefix, object_name = name.name.split('/')
    except:
        print("An error occurred splitting the string.")
    print(object_name)

相关问题 更多 >