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

时间:2019-06-21 20:40:18

标签: python google-cloud-platform

我正在尝试GCP参考上可用的python脚本将文件上传到Google云存储,但是每次运行它时,都会得到json密钥凭证文件找不到文件的错误,即使该文件与JSON密钥凭证文件位于同一目录中python脚本。

错误是:

  

文件“ c:\ users \ kundan \ appdata \ local \ programs \ python \ python37-
  32 \ lib \ site-         包\ google \ cloud \ client.py”,第75行,位于from_service_account_json           使用io.open(json_credentials_path,“ r”,encoding =“ utf-8”)作为       json_fi:         FileNotFoundError:[错误2]没有这样的文件或目录:'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)

1 个答案:

答案 0 :(得分:0)

这是我用来将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

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

  

回溯(最近一次通话最后一次):文件“ gcp_upload.py”,第9行,在          客户端= storage.Client.from_service_account_json('key.json')文件   “ E:\ Anaconda3 \ envs \ py35 \ lib \ site-packages \ google \ cloud \ client.py”,   第75行,位于from_service_account_json中       io.open(json_credentials_path,“ r”,encoding =“ utf-8”)作为json_fi:FileNotFoundError:[Errno 2]没有这样的文件或目录:   'key.json'

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

enter image description here

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