【问题标题】:Upload folder to google cloud bucket with python使用python将文件夹上传到谷歌云存储桶
【发布时间】:2021-04-14 20:33:13
【问题描述】:

我知道我可以像这样上传单个文件:

bucket_name = "my-bucket-name"
bucket = client.get_bucket(bucket_name)

blob_name = "myfile.txt"
blob = bucket.blob(blob_name)

blob.upload_from_filename(blob_name)

我怎样才能对文件夹做同样的事情?有类似blob.upload_from_foldername 的东西吗? 我尝试了相同的代码,将myfile.txt 替换为myfoldername,但没有成功。

FileNotFoundError: [Errno 2] No such file or directory: 'myfoldername'

这是文件夹结构:

我认为路径有问题,但我不确定是什么。我正在执行来自Untitled.ipynb 的代码。适用于myfile.txt,但不适用于myfoldername

我不想使用命令行功能。

【问题讨论】:

    标签: google-cloud-platform google-cloud-storage


    【解决方案1】:

    您无法在 Google Cloud Storage 中上传空文件夹或目录,但您可以使用客户端在 Cloud Storage 中创建空文件夹:

    from google.cloud import storage
    
    def create_newfolder(bucket_name, destination_folder_name):
        storage_client = storage.Client()
        bucket = storage_client.get_bucket(bucket_name)
        blob = bucket.blob(destination_folder_name)
    
        blob.upload_from_string('')
    
        print('Created {} .'.format(destination_folder_name))
    

    如果你想上传整个目录,你可以使用下面的代码:

    import glob
    import os 
    from google.cloud import storage
    
    client = storage.Client()
    def upload_from_directory(directory_path: str, destination_bucket_name: str, destination_blob_name: str):
        rel_paths = glob.glob(directory_path + '/**', recursive=True)
        bucket = client.get_bucket(destination_bucket_name)
        for local_file in rel_paths:
            remote_path = f'{destination_blob_name}/{"/".join(local_file.split(os.sep)[1:])}'
            if os.path.isfile(local_file):
                blob = bucket.blob(remote_path)
                blob.upload_from_filename(local_file)
    

    【讨论】:

    • 谢谢! destination_blob_name 将是我希望目录在存储桶中具有的名称?
    猜你喜欢
    • 2018-07-11
    • 2016-08-09
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多