python - 使用 Python 从谷歌云存储下载多个文件

标签 python python-3.x google-cloud-platform google-cloud-storage

我正在尝试从 Google 云存储文件夹下载多个文件。我可以下载单个文件,但无法下载多个文件。我从 this link 中获取了这个引用但似乎不起作用。 代码如下:

# [download multiple files]
bucket_name = 'bigquery-hive-load'
# The "folder" where the files you want to download are
folder="/projects/bigquery/download/shakespeare/"

# Create this folder locally
if not os.path.exists(folder):
    os.makedirs(folder)

# Retrieve all blobs with a prefix matching the folder
    bucket=storage_client.get_bucket(bucket_name)
    print(bucket)
    blobs=list(bucket.list_blobs(prefix=folder))
    print(blobs)
    for blob in blobs:
        if(not blob.name.endswith("/")):
            blob.download_to_filename(blob.name)

# [End download to multiple files]

有什么方法可以下载与模式(名称)或其他内容匹配的多个文件。由于我是从 bigquery 导出文件,因此文件名将如下所示:

shakespeare-000000000000.csv.gz
shakespeare-000000000001.csv.gz
shakespeare-000000000002.csv.gz
shakespeare-000000000003.csv.gz

引用:下载单个文件的工作代码:

# [download to single files]

edgenode_destination_uri = '/projects/bigquery/download/shakespeare-000000000000.csv.gz'
bucket_name = 'bigquery-hive-load'
gcs_bucket = storage_client.get_bucket(bucket_name)
blob = gcs_bucket.blob("shakespeare.csv.gz")
blob.download_to_filename(edgenode_destination_uri)
logging.info('Downloded {} to {}'.format(
    gcs_bucket, edgenode_destination_uri))

# [end download to single files]

最佳答案

经过一番尝试,我解决了这个问题,并且无法阻止自己也在这里发帖。

bucket_name = 'mybucket'
folder='/projects/bigquery/download/shakespeare/'
delimiter='/'
file = 'shakespeare'

# Retrieve all blobs with a prefix matching the file.
bucket=storage_client.get_bucket(bucket_name)
# List blobs iterate in folder 
blobs=bucket.list_blobs(prefix=file, delimiter=delimiter) # Excluding folder inside bucket
for blob in blobs:
   print(blob.name)
   destination_uri = '{}/{}'.format(folder, blob.name) 
   blob.download_to_filename(destination_uri)

关于python - 使用 Python 从谷歌云存储下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203883/

相关文章:

apache-spark - 如何将 PySpark 中的数据帧/RDD 以 CSV/Parquet 文件的形式快速保存到磁盘?

google-cloud-platform - GCP API网关返回403,表示托管服务 "is not enabled for the project"

python - python断言失败时如何退出?

python - 如何在 qlistwidget pyqt4 python 中添加带有文本的图像?

python - 改变Python中的不可变对象(immutable对象),方法?

python - anaconda python 错误导入 theano

django - 如何结合select_related()和value()? (2016年)

python-3.x - 使用python/flask在Google App Engine中以编程方式创建任务(推送)队列

从另一个文件夹中的脚本调用时,Python 未在同一文件夹中找到模块

apache-spark - Spark - 将 JDBC 驱动程序 JAR 添加到 Google Dataproc