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
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
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
To change the file object’s position, use f.seek(offset, from_what).
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