python - 我无法使用 python 脚本将文件上传到谷歌云?

标签 python google-cloud-platform

我正在尝试使用 GCP 引用上提供的 python 脚本将文件上传到谷歌云存储,但每次运行它时,我都会收到错误:找不到 json key 凭证文件的文件,即使它与 json key 凭证文件位于同一目录中 python 脚本。

错误是:

File "c:\users\kundan\appdata\local\programs\python\python37-
32\lib\site- packages\google\cloud\client.py", line 75, in from_service_account_json with io.open(json_credentials_path, "r", encoding="utf-8") as json_fi: FileNotFoundError: [Errno 2] No such file or directory: 'key.json'

代码如下:

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):

    storage_client = storage.Client.from_service_account_json(
    'key.json')
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

bucket='synersense_data'
source_file_name='gcp.txt'
destination_blob_name='prototype'

upload_blob(bucket,source_file_name,destination_blob_name)

最佳答案

这是我用来将 abc.txt 文件上传到 Google 存储的代码。

from google.cloud import storage

client = storage.Client.from_service_account_json('key.json')

def upload_blob(bucket_name, blob_name, filename):
    """ 
       Upload a blob to the bucket. 
       filename: source file name
       blob_name: destination blob name
    """
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)
    blob.upload_from_filename(filename)

print(upload_blob("XXXXXXXXXXXXXXX", "temp/abc.txt", "abc.txt"))

下面是输出:

enter image description here

最初,我也遇到了与您相同的错误:

Traceback (most recent call last): File "gcp_upload.py", line 9, in client = storage.Client.from_service_account_json('key.json') File "E:\Anaconda3\envs\py35\lib\site-packages\google\cloud\client.py", line 75, in from_service_account_json with io.open(json_credentials_path, "r", encoding="utf-8") as json_fi: FileNotFoundError: [Errno 2] No such file or directory: 'key.json'

我发现了我最初犯的错误。

enter image description here

检查 Google 存储凭证 json 名称是否为 key.jsonkey.json.json。有可能在重命名原始Google存储凭证json文件时,您将其命名为key.json,但重命名后会自动应用.json扩展名,因此它会已保存为 key.json.json 文件,但您在 storage.Client.from_service_account_json() 中传递 key.json (实际上需要为key.json.json)。尝试使用 lsdir 命令检查它。

关于python - 我无法使用 python 脚本将文件上传到谷歌云?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710197/

相关文章:

Kubernetes Cron 作业在创建下一个计划之前终止 Pod

macos - SSH 连接到 Google Cloud (GCP) 和 Google Compute Engine (GCE) 时,命令键 (⌘) 不再有效

python - 在 Python 中合并具有数百万行的两个表

google-cloud-platform - 从 Google Cloud Platform Cloud Shell 访问 GCP Memorystore

Python 未绑定(bind)方法错误

python - 将字符串值从 pickled 转换为字典

node.js - 使用 node.js 标准环境在 AppEngine 上找不到模块@google-cloud/firestore

kubernetes - "Limits"在 Kubernetes 集群中部署容器时忽略属性

python - 需要理解python中单行两个lambda的含义

嵌套字典和列表的 Pythonic 替代品