0

I have been getting an error where a '.txt' file that I have opened will not be detected by multiple loops.

hand = open('filter_test.txt')   # Open 1

# Loop 1
for line in hand:
    line = line.rstrip()
    if re.search(r'^X.*:', line):
        print(line)


# I can still see 'hand' here.
print(hand)

# If 'Open 2' is not there, the 'Loop 2' will not pick up 'filter_test.txt'

hand = open('filter_test.txt')    # Open 2

#Loop 2   
for line in hand:
    # If 'Open 2' is not present, line will not print anything here.
    print(line)
    line = line.rstrip()
    if re.search(r'^X-\S+:', line):
        print(line)

I can still see 'hand' between 'Loop 1' and 'Loop 2', but if I do not have the 'Open 2', 'Loop 2' will not pick it up.

Any idea why this is? It seems silly having to reopen a file for each loop I want to run

Cheers

GalacticPonderer
  • 497
  • 3
  • 16
  • 4
    close the file using `hand.close()` before you try to open it again – John May 25 '20 at 09:22
  • 2
    After the first for loop, you already read all the content of the file. There is nothing else to read, the second for loop is moot. – Keldorn May 25 '20 at 09:26
  • 1
    Does this answer your question? [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file) – Keldorn May 25 '20 at 09:31
  • 2
    @John The issue is not the supposedly missing `close()`. It is that the iterator reached the `StopIteration`, there is nothing else to iterate over. – Keldorn May 25 '20 at 09:35
  • I mean, thats why `close()` could be handy, to reset the reading of a file – John May 25 '20 at 10:03

1 Answers1

2

You can try

hand = open('filter_test.txt')  
hand_content = hand.read()
hand.close()

for line in hand_content:
    line = line.rstrip()
    if re.search(r'^X.*:', line):
        print(line)

print(hand_content)

for line in hand_content:
    print(line)
    line = line.rstrip()
    if re.search(r'^X-\S+:', line):
        print(line)

the problem was that you try to open a file that you didn't close the overcome for that is to store the file content in a variable and use the variable for the loops.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17