Remove a single row from a csv without copying files

后端 未结 7 2274
青春惊慌失措
青春惊慌失措 2020-12-06 00:07

There are multiple SO questions addressing some form of this topic, but they all seem terribly inefficient for removing only a single row from a csv file (usually they invol

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 00:42

    This is one way. You do have to load the rest of the file to a buffer, but it's the best I can think of in Python:

    with open('afile','r+') as fd:
        delLine = 4
        for i in range(delLine):
            pos = fd.tell()
            fd.readline()
        rest = fd.read()
        fd.seek(pos)
        fd.truncate()
        fd.write(rest)
        fd.close()
    

    I solved this as if you know the line number. If you want to check the text then instead of the above loop:

    pos = fd.tell()
    while fd.readline().startswith('Sarah'): pos = fd.tell()
    

    There will be an exception if 'Sarah' isn't found.

    This maybe more efficient if the line you are deleting is nearer to the end, but I'm not sure reading everything, dropping the line, and dumping it back will save much compared to user time (considering this is a Tk app). This also needs only to open and flush once to the file once, so unless files are extremely long, and Sarah is real far down it probably won't be noticeable.

提交回复
热议问题