2

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.

iamdlm
  • 1,885
  • 1
  • 11
  • 21
  • 1
    Wouldn't keeping the file be the same as overwriting the file with the lines removed? – Chris Jul 01 '20 at 22:43
  • 2
    You can't modify the file while you're reading it. Save what you want to keep in a list, then rewrite the file at the end. – Barmar Jul 01 '20 at 22:44
  • @Barmar Python has a library function for inplace editing: [**`fileinput.input`**](https://docs.python.org/3/library/fileinput.html#fileinput.input) – Peter Wood Jul 01 '20 at 22:57
  • with open('text.txt', 'r+') as f: line = 'x' read_ptr = 0 previos_write_ptr = 0 write_ptr = 0 while line: line = f.readline() print(line) read_ptr = f.tell() if line.strip() == 'keep': f.seek(write_ptr) f.write(line) write_ptr = f.tell() f.seek(read_ptr) f.seek(write_ptr) f.truncate() – Pramote Kuacharoen Jul 01 '20 at 23:25

2 Answers2

2

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,)
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

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
Red
  • 26,798
  • 7
  • 36
  • 58