【问题标题】:python delete files from google cloud storage that starts withpython从谷歌云存储中删除以开头的文件
【发布时间】:2022-12-09 19:14:20
【问题描述】:

使用 python 我也可以使用 prefixes 从存储桶中删除文件,但在 python 代码中,prefix means directory。 我想从 GCP 存储桶中删除以 example 开头的文件。

例如:

example-2022-12-07

example-2022-12-08

我跟着这个(Delete Files from Google Cloud Storage)但没有得到答案。

我正在尝试这个,但没有工作:

    blobs = bucket.list_blobs()
    fileList = [file.name for file in blobs if 'example' in file.name ]
    print(fileList)
    for file in fileList:
        blob = blobs.blob(file)
        blob.delete()
        print(f"Blob {blob_name} deleted.")
    

【问题讨论】:

  • 当您尝试运行代码时会发生什么?
  • 得到这个line 15, in deleter blob = blobs.blob(file) AttributeError: 'HTTPIterator' object has no attribute 'blob'
  • 这意味着 blobs 不是你想的那样。你查过bucket.list_blobs()的文档了吗?

标签: python google-cloud-storage


【解决方案1】:

您可以按照 Documentation 中的建议,尝试使用以下代码使用 blob.delete 方法从 Google Cloud Storage 中删除文件。

以下是您正在查找的示例:

from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket(bucket_name)
# list all objects in the directory
# Add prefix as parameter to bucket.list_blobs
blobs = bucket.list_blobs(prefix=?)
for blob in blobs: 
   blob.delete()
   print(f"Blob {blob_name} deleted.")`

您可以通过thread1thread2 查看。

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2018-09-24
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多