在Python中解析大型的,可能是压缩的文件

All*_*ynH 5 python gzip python-2.7

我试图逐行解析一个大文件,以获取相关信息.我可能正在接收未压缩或gzip压缩文件(我可能需要在稍后阶段编辑zip文件).

我使用下面的代码,但我觉得,因为我不在with语句中,我不是逐行解析文件,实际上是将整个文件加载file_content到内存中.

if ".gz" in FILE_LIST['INPUT_FILE']:
    with gzip.open(FILE_LIST['INPUT_FILE']) as input_file:
        file_content = input_file.readlines()
else:
    with open(FILE_LIST['INPUT_FILE']) as input_file:
        file_content = input_file.readlines()

for line in file_content:
    # do stuff
Run Code Online (Sandbox Code Playgroud)

有关如何处理此问题的任何建议?我宁愿不在代码块之外解压缩文件,因为这需要是通用的,我将不得不整理多个文件.

Jea*_*bre 5

readlines完全读取文件.所以对于大文件来说这是不行的.

像你一样做2个上下文块,然后使用input_file它们外面的句柄不起作用(在关闭文件上操作).

为了得到两全其美,我会使用用于上下文块一个三元条件(其确定opengzip.open必须使用),然后迭代上的行.

open_function = gzip.open if ".gz" in FILE_LIST['INPUT_FILE'] else open
with open_function(FILE_LIST['INPUT_FILE'],"r") as input_file:
    for line in input_file:
Run Code Online (Sandbox Code Playgroud)

请注意我添加了"r"模式以确保处理不在二进制上的文本(gzip.open默认为二进制)

替代方案:open_function可以通用,因此它不依赖于FILE_LIST['INPUT_FILE']:

open_function = lambda f: gzip.open(f,"r") if ".gz" in f else open(f)
Run Code Online (Sandbox Code Playgroud)

一旦定义,您可以随意重复使用它

with open_function(FILE_LIST['INPUT_FILE']) as input_file:
    for line in input_file:
Run Code Online (Sandbox Code Playgroud)

  • 不能取悦所有人:) lambda版本更好,因为它可以重复使用(我不喜欢复制/粘贴`FILE_LIST ['INPUT_FILE']`) (2认同)