-1

how to delete/remove a line from a .txt file after reading or printing

for x in open("words.txt",'r'):
print x
# Here i want to delete the line after printing and continue the loop

Can someone help me ?

3XDR
  • 3
  • 3

2 Answers2

0

In fact the best solution is not to write before you are not sure. If the data size isn't huge, the simpliest way is to load it to memory, than do whatever you want, than save.

lines = []
for x in open("words.txt"):
    lines.append(x)

#do something
#del lines[i] if you don't need them

for x in lines:
    print(x)

If the input file is big and you need only the last values to be erasable, you can store only the last values and drop them if you don't need. For saving the last values collections.deque is useful. The exact code will depend on the particular logic.

For the only one value to undo you can use this code

last_line = None
for x in open("words.txt"):
    if last_line is not None:
        print(last_line)
    last_line = x

    #do something
    #you may use continue or break

    #if you need undo "printing":
    #last_line = None
if last_line is not None:
    print(last_line)
Leonid Mednikov
  • 943
  • 4
  • 13
0
''.join([ x for x in open('file.txt').readlines() if x.strip() ])
smottt
  • 3,272
  • 11
  • 37
  • 44
Larcend
  • 66
  • 3