Deleting a line in a file

后端 未结 4 1807
感动是毒
感动是毒 2020-12-22 10:43

I am having an issue with a timetracker program, where I am trying to identify a line in a file by iterating over it and then writing the lines UNLESS there is anything with

4条回答
  •  佛祖请我去吃肉
    2020-12-22 11:24

    The problem comes from reading and writing the same file. Here is some explanation on that.

    Good reference (Beginner Python: Reading and writing to the same file)

    So when in r+ mode, both reading and writing to the file move the file pointer forward.

    So let's look at your example. First you do a readline. This moves the file pointer to the next line. You check if the line you just read is valid or not and write it if it is.

    The problem is that you just overwrote the next line, not the previous one! So your code is really messing up your data.

    Bascially it's really hard (and inefficient if the file is large) to do want you want to do right. You can't arbitrarily delete bytes out of the middle of a file. For each line you wanted to delete, you'd have to write the rest of the data over it then truncate the file at the end to delete the freed space.

    You should take the advice of the other answers and either output to another file or stdout.

提交回复
热议问题