Deleting a line in a file

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

    today.readline() returns a single line. The for-loop iterates over characters in that line. And as @gnibbler pointed out the today file is at the end of file at the time today.readline() is called (so it returns an emtpy string).

    In general, to delete something in the middle of a file you need to replace the file completely. fileinput module can help:

    import fileinput
    
    for line in fileinput.input([date], inplace=1):
        if delete not in line:
           print line, # stdout is redirected to the `date` file
    

    Here's almost the same but without fileinput:

    import os
    from tempfile import NamedTemporaryFile
    
    filename = date
    dirpath = os.path.dirname(filename)
    with open(filename) as file, NamedTemporaryFile("w", dir=dirpath) as outfile:
        for line in file:
            if delete not in line:
               print >>outfile, line, # copy old content
        outfile.delete = False # don't delete outfile
    os.remove(filename) # rename() doesn't overwrite on Windows
    os.rename(outfile.name, filename) # or just `os.replace` in Python 3.3+
    

提交回复
热议问题