I have a file with 100 entries.
If a record matches in the file as provided as input by the user, I want to delete that record content from the file.
How can I do this in python?
I have a file with 100 entries.
If a record matches in the file as provided as input by the user, I want to delete that record content from the file.
How can I do this in python?
with open(your_f) as f:
lines = f.readlines()
for ind, line in enumerate(lines):
if your condition: # if line contains a match
lines[ind] ="" # set line to empty string
with open(your_f,"w") as f: # reopen with w to overwrite
f.writelines(lines) # write updated lines
For example removing a line from a txt file that starts with 55:
with open("in.txt") as f:
lines = f.readlines()
for ind, line in enumerate(lines):
if line.startswith("55"):
lines[ind] = ""
with open("in.txt","w") as f:
f.writelines(lines)
input:
foo
bar
55 foobar
44 foo
output:
foo
bar
44 foo