Python truncate lines as they are read

后端 未结 7 618
梦毁少年i
梦毁少年i 2020-12-17 17:10

I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the li

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 17:25

    You can't. It is just not possible with actual text file implementations on current filesystems.

    Text files are sequential, because the lines in a text file can be of any length. Deleting a particular line would mean rewriting the entire file from that point on.

    Suppose you have a file with the following 3 lines;

    'line1\nline2reallybig\nline3\nlast line'
    

    To delete the second line you'd have to move the third and fourth lines' positions in the disk. The only way would be to store the third and fourth lines somewhere, truncate the file on the second line, and rewrite the missing lines.

    If you know the size of every line in the text file, you can truncate the file in any position using .truncate(line_size * line_number) but even then you'd have to rewrite everything after the line.

提交回复
热议问题