Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

Python delete row in file after reading it

I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.

There are two strategies to deleting from the middle of a file:

  1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.

  2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.

Number 1 is usually preferred since it is easier and doesn't require any locking.

Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...