如何在 Google Cloud Storage 上写入 XLSX 文件 [英] How to write to XLSX file on Google Cloud Storage

查看:22
本文介绍了如何在 Google Cloud Storage 上写入 XLSX 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 python 写入 Google Cloud Storage 上的 xlsx 文件?我现在正在这样做,但不确定如何格式化我的 write() 以连续添加.我想将 ['Sally', 'Ja', 15] 连续添加到云存储上的 names.xlsx 文件中.

How can I write to an xlsx file on Google Cloud Storage using python? I'm doing this right now but unsure how to format my write() to add in a row. I want to add in a row ['Sally', 'Ja', 15] to my names.xlsx file on cloud storage.

import cloudstorage

file = cloudstorage.open('/master/names.xlsx')
file.write(##what goes in here?##)
filehandle.close()

推荐答案

正如 Travis 所说,你不能追加而是重写整个对象,下面的例子(假设 text.csv 是你现有的文件),你可以阅读在 dataframe 中的文件,添加一些数据并使用 gsutil 命令将其复制到 GCP 存储桶.这将覆盖之前版本的 text.csv.

As mentioned by Travis , you cannot append but re-rewrite the entire object ,example below(assuming text.csv is your existing file) , you can read the file in dataframe , add some data and copy it using gsutil command to GCP bucket. This will overwrite the previous version of text.csv.

  import pandas as pd
  data = [['Alex','Feb',10],['Bob','jan',12]]
  df = pd.DataFrame(data,columns=['Name','Month','Age'])
  print df

输出

       Name Month  Age
    0  Alex   Feb   10
    1   Bob   jan   12

添加一行

  row = ['Sally','Oct',15]
  df.loc[len(df)] = row
  print df

输出

    Name Month  Age
0   Alex   Feb   10
1    Bob   jan   12
2  Sally   Oct   15

使用 gsutil 写入/复制到 GCP 存储桶

 df.to_csv('text.csv', index = False)
!gsutil cp 'text.csv' 'gs://BucketName/folderName/'

使用 python 写入/复制到 GCP 存储桶

`pip3 install xlsxwriter # install package`

python 代码

from google.cloud import storage
import pandas as pd

#define configurations
bucket_name = 'my_gcp_bucket'
xlsx_file = 'output.xlsx'

#create dataframe
data = [['Alex','Feb',10],['Bob','jan',12]]
df = pd.DataFrame(data,columns=['Name','Month','Age'])
df.to_excel("output.xlsx")

#Upload to Google cloud storage
client = storage.Client()
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(xlsx_file)
blob.upload_from_filename(xlsx_file)

这篇关于如何在 Google Cloud Storage 上写入 XLSX 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆