【问题标题】:Python delete row in file after reading itPython在读取文件后删除文件中的行
【发布时间】:2018-11-19 10:42:29
【问题描述】:

我是 python 2.7 我在 while 循环中从文件中读取数据。当我成功读取行时,我想从文件中删除这一行,但我不知道该怎么做 - 高效的方法,所以我不会浪费太多的 CPU。

    read = open("data.csv", 'r')
    for row in read:
        #code......
        if send == True:
            -->delete sent line from file, and continue to loop

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    在进行磁盘 IO 时,您不必担心 cpu 的使用——与几乎所有内存/cpu 操作相比,磁盘 IO 非常慢。

    从文件中间删除有两种策略:

    1. 将所有行写入辅助文件,然后将辅助文件重命名为原始文件名。

    2. 将文件的其余部分(尾部)复制到要删除的行的开头,然后从文件末尾截断 x 字节(其中 x 等于您要删除的行。

    通常首选数字 1,因为它更容易并且不需要任何锁定。

    Mayank Porwal 已为您提供了策略 #1 的大部分内容。以下是实施策略 2 的方法:

    # open the file for both reading and writing in binary mode ('rb+')
    with open('rmline.txt', 'rb+') as fp:   
        while 1:
            pos = fp.tell()       # remember the starting position of the next line to read
            line = fp.readline()
            if not line:
                break  # we reached the end of the file
    
            if should_line_be_skipped(line):  # only you know what to skip :-)
                rest = fp.read()  # read the rest of the file
                fp.seek(pos)      # go to the start position of the line to remove
                fp.write(rest)    # write the rest of the file over the line to be removed
                fp.truncate()     # truncates at current position (end of file - len(line))
                fp.seek(pos)      # return to where the next line is after deletion so we can continue the while loop
    

    【讨论】:

    • 是的,谢谢,我会这样做。因为我的问题是,例如,如果在读取大文件时计算机崩溃,当它再次出现时,它需要从头开始。但是这段代码会按照我的意愿进行,以循环存储。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 2017-03-02
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多