【问题标题】:How do I delete lines from a file 'in-place' without creating a temporary file?如何在不创建临时文件的情况下从文件“就地”删除行?
【发布时间】:2016-11-26 17:48:42
【问题描述】:

我为我正在编写的程序编写了 3 个单独的测试用例。不幸的是,我这样做填满了我的硬盘,也许大约 300+ gbs。我想从每个测试用例文件中抽取样本,然后删除文件的其余部分。

我知道如何在不消耗内存的情况下使用“readline”读取行,所以我可以从每个文件中取出一行并将其放入一个新文件中,然后使文件索引指向下一行而不是第一行行,从而释放存储空间。

这可以使用 python 库吗?

编辑:取出sed,它会创建一个临时文件

【问题讨论】:

  • 所以您已经知道如何获取单独的行,而您只想将它​​们写入一个新文件,或者您还想在没有第一行的情况下重写原始文件?
  • 我正在尝试就地重写原始文件,而不必将我当前未处理的行复制到内存中。
  • 然后让文件索引指向下一行你是怎么做到的?你是在 windows 还是 linux 上工作?
  • 好的 sed 没有做到这一点,它抛出了“没有剩余空间”的错误
  • sed 将重写整个文件。在大多数情况下,您必须这样做,因为文件是面向块的,它们一次并不是真正可寻址的行。可能有一些方法可以摆弄 inode 或其他东西,但复制通常是正确的方法。

标签: python algorithm file memory


【解决方案1】:

我想从每个测试用例文件中抽取样本,然后删除文件的其余部分。

从顶部逐行阅读。将要保留的部分写入文件的开头。保留文件中样本结束位置和未读部分开始位置的当前偏移量。

如果复制的部分可能与目的地重叠;使用类似于memmove(fp+current_offset, fp+unread_offset, count) 的算法:“从缓冲区的开头向前复制字节”。复制后:

current_offset += count
unread_offset += count

继续直到采集到足够的样本,然后调用file.truncate(current_offset) 删除文件中样本之后的所有内容。

例如,如果你想随机保留一半的行:

#!/usr/bin/env python
import random

with open('big-big.file', 'r+b') as file:
    current_offset = file.tell()
    while True:
        line = file.readline() # b'\n'-separated lines
        if not line: # EOF
            break
        if random.random() < 0.5: # keep the line
            unread_offset = file.tell()
            file.seek(current_offset)
            file.write(line)
            current_offset = file.tell()
            file.seek(unread_offset)
    file.truncate(current_offset)

【讨论】:

    【解决方案2】:

    这里尝试用mmap 重写文件。我不想填满我的硬盘,所以没有测试任何大的东西。它是一个可运行的示例,但您需要删除我用于测试的正面和背面的内容。

    这会将文件的前 50% 写入一个新文件,然后对其进行修剪。不确定这是否是您想要的顺序!

    import mmap
    
    import shutil
    import os
    from glob import glob
    
    files_to_trim = 'deleteme*'
    fraction_to_keep = .5
    blocksize = 128*1024
    
    # make test file
    open('deleteme1', 'w').writelines('all work and no play {}\n'.format(i)
        for i in range(6))
    open('deleteme2', 'w').writelines('all work and no play {}\n'.format(i)
        for i in range(10,18))
    
    
    with open('output', 'wb') as out:
        for filename in sorted(glob(files_to_trim)):
            st_size = os.stat(filename).st_size
            sample_size = int(st_size * fraction_to_keep)
            with open(filename, 'r+b') as infile:
                memfile = mmap.mmap(infile.fileno(), 0)
                # find next line ending
                need_newline = False
                count = memfile.find(b'\n', sample_size)
                if count >= 0:
                    count += 1 # account for \n
                else:
                    count = st_size
                    need_newline = memfile[-1] == '\n'
                # copy blocks to outfile
                for rpos in range(0, count+blocksize-1, blocksize):
                    out.write(memfile[rpos:min(rpos+blocksize, count)])
                if need_newline:
                    out.write('\n')
                # trim infile
                remaining = st_size - count
                memfile[:remaining] = memfile[count:]
                memfile.flush()
                memfile.close()
                infile.truncate(remaining)
                infile.flush()
    
    # validate test file
    print('deleteme1:')
    print(open('deleteme1').read())
    print('deleteme2:')
    print(open('deleteme2').read())
    print('output:')
    print(open('output').read())
    

    【讨论】:

    • 好的,如果你改变了填充硬盘的想法,我可以给你我的测试用例生成器。
    • ...或者你可以检查你的东西是否被炸成碎片! - 微笑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2012-09-16
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多