For循环无法在同一文件描述符上运行两次 [英] For loop not working twice on the same file descriptor
本文介绍了For循环无法在同一文件描述符上运行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该代码未进入第二个for循环.我没有在任何地方修改文件描述符.为什么会这样呢?
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:
会将读取指针,文件指针或任何被调用的内容放在文件末尾.在您的for
循环之间调用fd.seek(0)
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
这篇关于For循环无法在同一文件描述符上运行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文