使用Google Cloud Storage API处理大文件

时间:2015-07-25 07:12:01

标签: python file append google-cloud-storage cloud-storage

我需要实现的是使用cloudstorage库将文件列表连接到单个文件中。这需要在mapreduce分片内部发生,该分片在内存上有512MB的上限,但是连接的文件可能大于512MB。

当文件大小达到内存限制时,以下代码段会中断。

list_of_files = [...]
with cloudstorage.open(filename...) as file_handler:
    for a in list_of_files:
        with cloudstorage.open(a) as f:
            file_handler.write(f.read())

有没有办法解决这个问题?也许在块中打开或追加文件?怎么做?谢谢!

==编辑==

经过多次测试后,似乎内存限制仅适用于f.read(),而写入大文件是可以的。以块的形式读取文件解决了我的问题,但我非常喜欢@ {I--Lewis指出的compose()函数。谢谢!

1 个答案:

答案 0 :(得分:2)

对于大文件,您需要将文件分解为较小的文件,上传其中的每个文件,然后将它们合并为composite objects。您将需要使用库中的compose() function。似乎有no docs on it yet

在您上传了所有部件后,以下内容应该有效。要确保的一件事是要编写的路径文件在开头不包含存储桶名称或斜杠。

stat = cloudstorage.compose(
    [
        "path/to/part1",
        "path/to/part2",
        "path/to/part3",
        # ...
    ],
    "/my_bucket/path/to/output"
)

如果可能,您可能还想使用gsutil工具结账。它可以为你做automatic splitting, uploading in parallel, and compositing of large files