gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:43:50 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com