【问题标题】:How to stream data line by line from bucket to python script如何将数据从存储桶逐行流式传输到 python 脚本
【发布时间】:2019-09-30 16:20:42
【问题描述】:

我正在处理存储在 Google Cloud 中的大型数据文件。我正在使用一个 Python 脚本,它首先下载一个包含 json 行的 blob,然后打开它以逐行分析数据。这种方法非常慢,我想知道是否存在更快的方法来做到这一点。从命令行我可以使用gsutil cat 将数据流式传输到标准输出,是否有类似的方法可以在 Python 上执行此操作?

这是我目前读取数据的方式:

myClient = storage.Client()
bucket = myClient.get_bucket(bucketname)
blob = storage.blob.Blob(blobname, bucket)
current_blob.download_to_filename("filename.txt")

file = open("filename.txt", "r")
data = f.readlines()

for line in data:
    # Do stuff

我想逐行读取 blob,无需等待下载。

编辑:我发现了这个answer,但我不清楚这个功能。我不知道如何阅读流线。

【问题讨论】:

    标签: python google-cloud-platform


    【解决方案1】:

    answer you found 中,stream 是一个类文件对象,因此您应该能够使用它而不是打开特定的文件名。像这样的东西(未经测试):

    myClient = storage.Client()
    bucket = myClient.get_bucket(bucketname)
    blob = storage.blob.Blob(blobname, bucket)
    stream = open('myStream','wb', os.O_NONBLOCK)
    streaming = blob.download_to_file(stream)
    
    for line in stream.readlines():
        # Do stuff
    

    【讨论】:

    • 我试过了,它给了我错误 for line in stream.readlines(): io.UnsupportedOperation: read 。如何使对象可读?
    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2016-08-10
    • 1970-01-01
    • 2017-05-29
    • 2019-10-14
    相关资源
    最近更新 更多