For loop not working twice on the same file descriptor [duplicate]

Posted on

Question :

For loop not working twice on the same file descriptor [duplicate]

The code is not entering the second for loop. I am not modifying the file descriptor anywhere. Why is that happening?

import os
import re

path = '/home/ajay/Desktop/practice/ajay.txt'
fd = open(path,'r+')
interfaces = []
tx_packets = []

for line in fd:

    inter = re.match(r'(w+)s+Link',line)
    interface =

for lines in fd:

    if('s+TX packets:(d+)',lines)):
        tx_packs = re.match(r's+TX packets:(d+)',lines)
        tx_pack =

print interfaces
print  tx_packets
Asked By: Ajay J


Answer #1:

Because for lines in fd: will place the read pointer, file pointer or whatever it’s called at the end of the file. Call in between your for loops

Answered By: jDo

Answer #2:

That is because your file pointer has reached the end of the file. So you need to point it back to the beginning of the file before your next iteration. Put this before your second loop:

Check the tutorial on input/output here. The part about seek states:

To change the file object’s position, use, from_what).

Answered By: idjaw

Answer #3:

The for loop works by calling until it raises StopIteration. When you iterate through it the second time, the file has already finished. To get back to the beginning, use

Answered By: zondo

Leave a Reply

Your email address will not be published. Required fields are marked *