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
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+