如何在有限的环境中从Python中删除大文件中的行

Jam*_*Lin 6 python file lines

假设我在美国有一个10GB的硬盘Ubuntu VPS(我住在其他地方),我在硬盘上有一个9GB的文本文件.我有512MB的RAM,大约相同的交换量.

鉴于我无法添加更多硬盘空间并且无法将文件移动到其他地方进行处理,是否有一种有效的方法可以使用Python从文件中删除一些行(最好是,但是任何其他语言都可以接受)?

DMA*_*361 3

这个怎么样?它就地编辑文件。我已经在一些小文本文件(Python 2.6.1)上测试了它,但由于所有的跳跃,我不确定它在大文件上的表现如何,但仍然......

我使用了带有手动 EOF 检查的不定 while 循环,因为它for line in f:无法正常工作(大概所有的跳转都会扰乱正常的迭代)。可能有更好的方法来检查这一点,但我对 Python 比较陌生,所以请有人告诉我是否有。

此外,您还需要定义该函数isRequired(line)

writeLoc = 0
readLoc = 0
with open( "filename" , "r+" ) as f:
    while True:
        line = f.readline()

        #manual EOF check; not sure of the correct
        #Python way to do this manually...
        if line == "":
            break

        #save how far we've read
        readLoc = f.tell()

        #if we need this line write it and
        #update the write location
        if isRequired(line):
            f.seek( writeLoc )
            f.write( line )
            writeLoc = f.tell()
            f.seek( readLoc )

    #finally, chop off the rest of file that's no longer needed
    f.truncate( writeLoc )
Run Code Online (Sandbox Code Playgroud)