【问题标题】:writing a simple text file with no key value pair to cloud storage storage将没有键值对的简单文本文件写入云存储
【发布时间】:2021-12-06 21:06:52
【问题描述】:

我的要求是以特定的排序顺序将数据从 BQ 导出到 GCS,我无法使用自动导出来获得,因此尝试为此编写手动导出。 文件格式如下:

HDR001||5378473972abc||20101|182082||
DTL001||436282798101|
DTL002||QS
DTL005||3733|8
DTL002||QA
DTL005||3733|8
DTL002||QP
DTL005||3733|8
DTL001||436282798111|
DTL002||QS
DTL005||3133|2
DTL002||QA
DTL005||3133|8
DTL002||QP
DTL005||3133|0

我对此很陌生,能够将文件写入本地磁盘,但我不确定如何将其写入文件到 GCS。我尝试使用 write_to_file,但似乎遗漏了一些东西。

import pandas as pd
import pickle as pkl
import tempfile
from google.colab import auth
from google.cloud import bigquery, storage

#import cloudstorage as gcs auth.authenticate_user()

df = pd.DataFrame(data=job)

sc = storage.Client(project='temp-project')
with tempfile.NamedTemporaryFile(mode='w+b', buffering=- 1,prefix='test',suffix='temp') as fh:
    with open(fh.name,'w+',newline='') as f:
        dfAsString = df.to_string(header=" ", index=False)
        fh.name = fh.write(dfAsString)
        fh.close()

bucket = sc.get_bucket('my-bucket')
target_fn = 'test.csv'
source_fn = fh.name
destination_blob_name = bucket.blob('test.csv')

bucket.blob(destination_blob_name).upload_from_file(source_fn)

有人可以帮忙吗?

谢谢。

【问题讨论】:

标签: python google-bigquery google-cloud-storage


【解决方案1】:

我建议通过 Cloud Storage 存储分区上传对象。您需要使用upload_from_filename 而不是upload_from_file。您的代码应如下所示:

bucket.blob(destination_blob_name).upload_from_filename(source_fn)

这里是有关如何upload an object to Cloud Storage bucketClient library 文档的文档的链接。

编辑:

之所以会这样,是因为在代码的某个地方,您传递的是 Blob 对象,而不是字符串。目前您的目标变量是一个 Blob 对象,请将其改为字符串:

destination_blob_name = bucket.blob('test.csv')

destination_blob_name = 'test.csv'

【讨论】:

  • 谢谢,但是当我尝试 upload_from_file 或 upload_from_filename 时,我收到错误 ValueError: 无法转换为统一码
  • 我已经编辑了我的答案。请检查。
  • @Niti 你有时间检查答案吗?它是否帮助您解决了您的问题?如果是,请考虑接受。 What should I do when someone answers my question?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多