2

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
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Ajay J
  • 33
  • 3
  • Because `for lines in fd:` will place the read pointer or whatever it's called at the end of the file. Call `fd.seek(0)` in between your `for` loops – jDo Apr 12 '16 at 01:18

3 Answers3

3

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).

idjaw
  • 25,487
  • 7
  • 64
  • 83
2

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)

zondo
  • 19,901
  • 8
  • 44
  • 83
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

jDo
  • 3,962
  • 1
  • 11
  • 30