Python中大文件中的行分割引起的内存问题 - python

我正在尝试从磁盘读取一个大文件(〜2GB),并将每一行拆分为多个字符串:

def get_split_lines(file_path):
    with open(file_path, 'r') as f:
        split_lines = [line.rstrip().split() for line in f]
    return split_lines

问题是,它试图在内存中分配数十个GB。我发现如果以以下方式更改代码不会发生这种情况:

def get_split_lines(file_path):
    with open(file_path, 'r') as f:
        split_lines = [line.rstrip() for line in f]    # no splitting
    return split_lines

即,如果我不分割线,则内存使用会急剧下降。
有什么办法可以解决这个问题,也许是一些聪明的方法来存储分割行而不填满主存储器?

感谢您的时间。

python大神给出的解决方案

拆分之后,您将拥有多个对象:一个元组和一些字符串对象。除了组成原始字符串的实际字符集之外,每个对象都有自己的开销。

与其将整个文件读入内存,不如使用生成器。

def get_split_lines(file_path):
    with open(file_path, 'r') as f:
        for line in f:
            yield line.rstrip.split()

for t in get_split_lines(file_path):
    # Do something with the tuple t 

这并不妨碍您编写类似

lines = list(get_split_lines(file_path))

如果确实需要将整个文件读入内存。