使用Cloud Shell查看云存储中的文件

时间:2017-09-28 01:53:07

标签: python google-cloud-storage

我一直是Google Cloud Platform的新工作,我希望从存储桶读取文件,进行一些转换,然后最终将转换后的数据保存回云端存储。截至目前,我无法读取数据并查看文件名。我能否从如何最佳地读取和转换数据库中的数据?

这是我的代码:

from google.cloud import storage
from google.cloud.storage import Blob

bucket_name = 'test_bucket'
file_name = '*.txt'
client = storage.Client()

bucket = client.get_bucket(bucket_name)

for f in bucket:
    print(f)

TypeError:' Bucket'对象不可迭代

blob = bucket.get_blob(file_name)
print(blob)

print(blob.download_as_string())

AttributeError:' NoneType'对象没有属性' download_as_string'

2 个答案:

答案 0 :(得分:2)

你想:

bucket = client.get_bucket(bucket)
for f in bucket.list_blobs():
  print(f)

对于referenec,文档位于:https://googlecloudplatform.github.io/google-cloud-python/latest/storage/buckets.html

您不能使用" * .txt"等通配符。您可以设置前缀,但是如果您想要查找以" .txt"结尾的内容,您必须遍历所有内容并自行过滤。

答案 1 :(得分:0)

最好在调用bucket.get_blob(filename)之后检查返回的对象类型,以确保不会发生NoneType错误:

blob = bucket.get_blob(file_name)
if blob is not None and blob.exists(client):
   blob.download_as_string()