- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试使用 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"))
下面是输出:
最初,我也遇到了与您相同的错误:
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'
我发现了我最初犯的错误。
检查 Google 存储凭证 json 名称是否为 key.json
或 key.json.json
。有可能在重命名原始Google存储凭证json文件时,您将其命名为key.json
,但重命名后会自动应用.json
扩展名,因此它会已保存为 key.json.json
文件,但您在 storage.Client.from_service_account_json()
中传递 key.json
(实际上需要为key.json.json
)。尝试使用 ls
或 dir
命令检查它。
关于python - 我无法使用 python 脚本将文件上传到谷歌云?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710197/
我是一名优秀的程序员,十分优秀!