我开始使用 Google Cloud Storage python API,并遇到了一个奇怪的错误。
某些文件夹未随 API 调用返回,就像它们不存在一样。
我尝试了以下代码:
• 列出父目录中的文件/文件夹:
storage_client.list_blobs(bucket_or_name=bucket, prefix=path)
我的文件夹未在迭代器中列出
• 检查是否存在:
bucket.get_blob(path + "/my_folder").exists()
获取AttributeError
因为NoneType没有属性exists()
(即找不到blob)
• 尝试列出其中的文件:
storage_client.list_blobs(bucket_or_name=bucket, prefix=path + "/my_folder")
并获取零长度迭代器
该文件夹的路径是从 Google Cloud Console 复制的,并且它确实存在。那为什么我看不到呢?我错过了什么吗?
最佳答案
感谢约翰·汉利,我意识到了自己的错误。我想错了。
Google Cloud Storage 中没有文件夹,代码返回给我的“文件夹”只是空文件(但并非每个文件夹都有空文件来表示它)。
所以我编写了这段代码,它返回存储中文件(和“文件夹”)的生成器:
def _iterate_files(storage_client, bucket: Bucket, folder_path: str, iterate_subdirectories: bool = True):
blobs = storage_client.list_blobs(bucket_or_name=bucket,
prefix=folder_path.rstrip('/') + "/",
delimiter='/')
# First, yield all the files
for blob in blobs:
if not blob.name.endswith('/'):
yield blob
# Then, yield the subfolders
for prefix in blobs.prefixes:
yield bucket.blob(prefix)
# And if required, yield back the files and folders in the subfolders.
if iterate_subdirectories:
yield from _iterate_files(bucket, prefix, True)
关于Python Google Cloud Storage 未列出某些文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71150275/