【问题标题】:How to write to XLSX file on Google Cloud Storage如何在 Google Cloud Storage 上写入 XLSX 文件
【发布时间】:2019-02-15 19:36:22
【问题描述】:

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

import cloudstorage

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

【问题讨论】:

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


    【解决方案1】:

    正如 Travis 所提到的,您不能附加而是重写整个对象,例如下面的示例(假设 text.csv 是您现有的文件),您可以读取数据框中的文件,添加一些数据并使用 gsutil 命令将其复制到GCP 存储桶。这将覆盖之前版本的 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)
    

    【讨论】:

    • 但我希望我的谷歌应用引擎应用程序创建一个 xlsx 文件并存储在谷歌存储中。这个方法不行
    • @John 用 python 代码更新了我的帖子以访问 GCS 存储桶。
    • @eric chen,请参考我的帖子
    【解决方案2】:

    Google Cloud Storage 中的对象是不可变的,因此您不能将新行附加到现有对象。您需要重写整个对象。

    您可以使用compose API 获得有限的“附加”功能,但这只会将字节附加到对象的末尾并将字节附加到对象的末尾,我不相信这可以轻松实现XLSX 数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2023-03-05
      • 2020-12-01
      • 2019-02-14
      • 2020-05-05
      相关资源
      最近更新 更多