将没有键值对的简单文本文件写入云存储

2024-10-03 06:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的要求是以特定的排序顺序将数据从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_文件,但似乎遗漏了一些内容

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

#将cloudstorage作为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)

有人能帮忙吗

多谢各位


Tags: 文件namefromtestimportbucket顺序as
1条回答
网友
1楼 · 发布于 2024-10-03 06:19:27

我建议通过云存储桶上传一个对象。您需要使用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'

相关问题 更多 >