如何创建一个新的CSV文件,然后将其存储在Google Cloud Storage中?

时间:2019-05-17 18:41:56

标签: python csv google-cloud-platform google-cloud-storage

我有此代码:

import csv
from google.cloud import storage
import os

os.environ["Credientials"]
storage_client = storage.Client()

mylist = ['Row1','Row2','Row3']  # Rows I'm making for CSV file

with open('Afile.csv', 'w') as myfile:
   wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)  # Making CSV file
   wr.writerow(mylist)

s = myfile

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('BucketName', s ,'storage location') # Uploading the newly made CSV file to Google Cloud Storage

在创建新的CSV文件(由s引用)的情况下,我正在尝试将该新创建的文件上传到Google Cloud存储,而不是从本地文件路径上传。运行此命令时,出现以下错误:

TypeError: expected string or bytes-like object

如何使它正常工作,以便我可以制作一个新的CSV文件,然后将其上传到Google Cloud Storage?如果可能的话?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

with open('Afile.csv', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)  # Making CSV file
    wr.writerow(mylist)

    s = myfile

此处sfile like object,而不是字符串或字节对象。您实际上是在传递文件本身,而不是传递文件名。您可能应该将Afile.csv作为字符串传递。