The correct way is to first the read the content completely, make your modifications and then write back to the file.
This approach is clean and readable too.
#first read everything
with open('file_name','r') as f:
content = f.read()
#now perform modifications
content = content.replace('foo 69','')
#now write back to the file
with open('file_name','w') as f:
f.write(content)
Now, I've commented some of the problems you had in your code:
with open('file_name','a+') as f:
for line in f:#here you are iterating through the content of the file
# at each iteration line will equal foo 69, then bar 70 and then bar 71...
# Now, there is no reason to open the file here again, I guess you opened
# it to write again, but your mode is set to `a` which will append contents
# not overwrite them
with open('contacts.txt','a+') as f:
if "foo" in line:
line.replace("foo", "") #here the modified content is lost
# because you're not storing them anywhere
Edit - As mentioned in the comments, if your file is quite large and you do not want to read all the contents.
Then the best way to do this is to read the content line by line and write contents to another file excluding the line you want to delete.
to_replace = 'foo 69\n' #note \n is neccessary here
with open('input.txt','r') as input_file:
with open('ouput.txt','w') as output:
for line in input_file:
if line!=to_replace:
output.write(line)
#Now, let's say you want to delete all the contents of the input_file
#just open it in write mode and close without doing anything
input_file = open('input_file.txt','w')
input_file.close()
# If you want to delete the entire input_file and rename output_file to
# original file_name then you can do this in case of linux OS using subprocess
subprocess.call(['mv', 'output_file.txt', 'input_file.txt'])
This is very memory efficient because only a single line of content is in memory at any point of time. input_file
is only a pointer to the file and the iteration - for line in input_file
does not read the whole file and start iterating the content one by one.