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'
os.system('ifconfig>>path')
fd = open(path,'r+')
interfaces = []
tx_packets = []

for line in fd:

    if(re.search(r'(w+)s+Link',line)):
    inter = re.match(r'(w+)s+Link',line)
    interface = inter.group(1)
    interfaces.append(interface)

for lines in fd:

    if(re.search(r's+TX packets:(d+)',lines)):
        tx_packs = re.match(r's+TX packets:(d+)',lines)
        tx_pack = tx_packs.group(1)
        tx_packets.append(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 fd.seek(0) 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:

fd.seek(0)

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

To change the file object’s position, use f.seek(offset, from_what).

Answered By: idjaw

Answer #3:

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

Answered By: zondo

Leave a Reply

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