1

Basically, I have a test.txt file where my goal is to

  1. Read the first line
  2. Use the current first line
  3. delete the current line so the next comes first in the file
  4. Repeat until EOF

I know I could store the file in a list, but I'm looking for a way to accomplish using an iterator.

I have tried,

with open("test.txt", "r") as f:
    for line in f:
        print(line) #Use the line in some way (example purposes)
        # del line (looking for something like this maybe)

Which logically doesn't work since I'm not writing to the file. What would be the best way to accomplish this in Python using an iterator?

scharette
  • 9,437
  • 8
  • 33
  • 67
  • I understand the question, out of curiosity what sort of use case is this? Initially I thought it might be for creating multiple files from a single file. If a file contains n lines, create 'n' subfiles, but not sure what is the use case. Can you please explain? – madmatrix Jul 23 '18 at 14:57
  • Why do you need to delete the line? Can't you just loop on the lines and use them one after the others until EOF? – Mathieu Jul 23 '18 at 14:58
  • Actually, the idea came from [another question](https://stackoverflow.com/q/51479759/7692463) where a great answer from @StevenRumbalski arised in the comments section of an answer and I thought that it had its place in a real question. Basically, I guess OP wanted to re-use the same file to read data from it. I felt like it was real bad practice to have a valid answer as a comment while it could be beneficial for future users. – scharette Jul 23 '18 at 15:00
  • See in particular the [answer](https://stackoverflow.com/questions/42630639/how-to-read-and-delete-first-n-lines-from-file-in-python-elegant-solution/42630862#42630862) by @brunodesthuilliers to the marked duplicate question. – Steven Rumbalski Jul 23 '18 at 15:12

0 Answers0