Deleting a line in a file

后端 未结 4 1800
感动是毒
感动是毒 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:14

    This is reading to the end of the file

    print(today.read())
    

    When you start iterating here, you're already at the end

    for line in today.readline():
    

    so the for loop will never be entered. You need to reopen the file or seek back to the beginning.

    Another problem is that you are iterating over the first line. You probably meant

    for line in today:
    

    Regardless, it's generally not a great idea to write to the same file you are reading (eg. consider the mess the file would be in if the computer gets reset partway through)

    Better to write a temporary file and replace.

    If the files are very small, you could read the file into a list in memory and then rewrite the file out again.

    A better idea, before you go too far is to use a database such as the sqlite module (which is builtin to Python)

提交回复
热议问题