如何在Google Cloud Storage上写入XLSX文件 [英] How to write to XLSX file on Google Cloud Storage
问题描述
如何使用python写入Google Cloud Storage上的xlsx文件?我现在正在执行此操作,但是不确定如何格式化我的write()以添加到一行中.我想在云存储上的names.xlsx文件中添加一行['Sally','Ja',15].
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屋!