使用 python 将文件上传到 Google 云平台上的存储桶时出现问题

Issue when uploading a file to a bucket on Google cloud platfrom using python

当我将文本文件上传到 GCP 中的存储桶时(使用 python),文件大小为 0KB,并且文件不包含任何内容。

代码:

from google.cloud import storage

f = open("myText.txt", "w")
f.write("Yo\n")
f.write("awe")

def upload_blob(bucket_name, source_file_name, destination_blob_name):
  """Uploads a file to the bucket."""


  storage_client = storage.Client()

  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))


upload_blob('dev_kfp', 'myText.txt', "myTextOnline.txt")

文件上传时出现 0 个错误,但文件大小为 0Kb,并且文件不包含任何内容。请协助。当我在文件资源管理器中打开文件时,它确实包含内容。 GCP 存储桶上的文件类型为 text/plain。

谢谢!

我能够重现您的问题,并且根据@mjkool 关闭脚本上的文件后,上传的文件具有存储桶中的大小。这是更新后的脚本:

#!/usr/bin/env python3

from google.cloud import storage

f = open("myText.txt", "w")
f.write("Yo\n")
f.write("awe")
f.close()

def upload_blob(bucket_name, source_file_name, destination_blob_name):
  """Uploads a file to the bucket."""


  storage_client = storage.Client()

  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))


upload_blob('my_bucket', 'myText.txt', "myTextOnline.txt")