-1

When I make a for loop for a line in a text file and print the line then remove it. It removes the consecutive line not the line I printed. I want it to print the line then delete it. I need this to finally complete my brute force script.

file = input("Enter the list:")

with open(file) as f:
    file = list(f)

while True:
   for line in file:
     try:
         print(line)
         file.remove(line)
     except:
         print("of course")
glhr
  • 4,439
  • 1
  • 15
  • 26
ALEX
  • 13
  • 1
  • 1
    Why are you trying to open a string as a file? – glhr Apr 30 '19 at 22:48
  • Are you trying to delete lines from the file on disk, or from the list in memory? Originally `file` is the name of a file on disk, but later it is a list of rows from that file, with no connection to the original file (i.e. deleting from this list won’t affect the file on disk). – Matthias Fripp Apr 30 '19 at 23:46

1 Answers1

0

You wrote file = list(f) where the usual idiom would be to assign f.readlines(), but that's fine.

Then you mutate a list while iterating over it. That's a little more of a problem. Also, using pop(0) would be more natural than asking remove() to search for a value matching line (which should be the first value encountered).

Here is a simpler example of mutating while iterating:

>>> lst = [4, 5, 6]
>>> for item in lst:
...   print(lst.pop(0))
... 
4
5

Popping within the loop interferes with the iteration, which is expected because we shouldn't have been mutating during iteration in the first place. The item variable never takes on the value 5.

Making a copy and iterating over that is one way out:

>>> lst = [4, 5, 6]
>>> for item in list(lst):
...   print(lst.pop(0))
... 
4
5
6

Perhaps you don't want to make a copy of the list. This code looks more like Fortran than Python, but the behavior it shows is probably closer to what you were hoping for.

>>> lst = [4, 5, 6]
>>> for i in range(len(lst)):
...   print(i, lst.pop(0))
... 
0 4
1 5
2 6
J_H
  • 17,926
  • 4
  • 24
  • 44