如何将数据逐行从存储桶流式传输到 python 脚本



我正在处理存储在Google Cloud中的大数据文件。我正在使用一个 Python 脚本,它首先下载一个包含 json 行的 blob,然后打开它以逐行分析数据。这种方法非常慢,我想知道是否存在更快的方法来做到这一点。从命令行我可以使用gsutil cat将数据流式传输到 stdout,在 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,而无需等待下载。

编辑:我找到了这个答案,但我不清楚该功能。我不知道如何阅读流线。

在你找到的答案中,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

使用 BlobReader。

from google.cloud import storage
client = storage.Client()
bucket = client.bucket(bucketname)
blob = bucket.blob(blobname)
reader = storage.fileio.BlobReader(blob)
for line in reader:
# Do stuff with each line

最新更新