Remove current line from file

Viewed 74

Consider a file with the following lines:

remove   
keep
remove

Is it possible to remove the current line while iterating the file lines?

for word in file:
    if word != "keep":
        remove_line_from_file

In the end the file should just the line with word keep.
I know I could create a file with the remaining words but I was hoping to keep the same file.

2 Answers

Python has a nice library named fileinput which allows you to modify files inplace. You can print what you want to keep back into the file:

with fileinput.input(filename, inplace=True) as lines:
    for line in lines:
        if line == 'keep':
            print(line,)

No, but you can extract all the contents of the file beforehand,
modify the text, and then rewrite them back into the file:

with open('file.txt','r') as f:
    lines = f.readlines()

with open('file.txt','w') as f:
    f.write(''.join([ln for ln in lines if 'keep' in ln])) # Writes all the lines back to file.txt that has the word `keep` in them
Related