【问题标题】:FileNotFoundError when trying to access a file in google cloud that exists inside a bucket storage尝试访问存储桶存储中存在的谷歌云中的文件时出现 FileNotFoundError
【发布时间】:2021-06-22 21:28:52
【问题描述】:

FileNotFoundError 尝试通过引用gs://BUCKET_NAME/FolderName/ 读取/访问存在于谷歌云存储桶中的文件或文件夹时。

我使用 python 3 作为带有 jupyter notebook 的内核。我在链接到存储桶的谷歌云中配置了一个集群。当我尝试读取/上传文件时,我收到文件未找到错误

def get_files(bucketName):
    files = [f for f in listdir(localFolder) if 
    isfile(join(localFolder, f))]
    for file in files:
        print("file path:", file)

get_files("agriculture-bucket-gl")

我应该能够访问文件夹内容或引用存储桶中任何文件夹中存在的任何文件。

错误信息:

FileNotFoundError: [Errno 2] No such file or directory: 'gs://agriculture-bucket-gl/Data sets/'

【问题讨论】:

  • 缺少一些代码。你是怎么得到你的文件的?如果硬编码路径,是否还有问题?
  • 是的,我正在对路径进行硬编码,但问题仍然存在。例如:localFolder = "gs://agriculture-bucket-gl/Data sets/'
  • 当你从不使用 bucketName 作为参数时,为什么要传递它?
  • 当您在名为gs://mybucket/file.txt 的文件上调用open() 时,open() 函数不会神奇地知道gs:// 前缀的意思是“从亚马逊存储桶获取此文件”;它只是认为这是一个普通的文件名,当然不是。

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


【解决方案1】:

您需要使用存储库访问存储桶,获取文件然后获取内容。

您可能会发现此代码模板很有帮助。

from google.cloud import storage

# Instantiates a client
client = storage.Client()

bucket_name = 'your_bucket_name'

bucket = client.get_bucket(bucket_name)

blob = bucket.get_blob('route/to/file.txt')

downloaded_blob = blob.download_as_string()

print(downloaded_blob)

【讨论】:

    【解决方案2】:

    如果你想从存储访问

    from google.cloud import storage
    
    bucket_name = 'your_bucket_name'
    blob_path = 'storage/path/fileThatYouWantToAccess'
    
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_path)
    
    #this is optional if you want to download it to tmp folder
    blob.download_to_filename('/tmp/fileThatYouWantToAccess')
    

    【讨论】:

      【解决方案3】:

      为了补充前面的答案,Error Message: FileNotFoundError: [Errno 2] No such file or directory: 'gs://agriculture-bucket-gl/Data sets/' 中的路径也包含一些问题。我会尝试修复以下问题:

      • 文件夹名称“数据集”有一个空格。我会尝试一个没有空格的名称。
      • / 符号位于路径的末尾。路径应以不带斜线结尾。

      【讨论】:

        猜你喜欢
        • 2019-08-24
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 2016-11-01
        • 2020-04-22
        相关资源
        最近更新 更多