For循环在同一个文件descrip上不工作两次

2024-09-28 01:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

代码没有进入第二个for循环。我不会在任何地方修改文件描述符。为什么会这样?在

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

Tags: pathinimportreforsearchifos
3条回答

这是因为你的文件指针已经到达文件的末尾。因此,您需要在下一次迭代之前将其指向文件的开头。在第二个循环之前:

fd.seek(0)

查看关于输入/输出here的教程。{cd1>关于部件的状态:

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

for循环的工作原理是调用fd.next(),直到它引发StopIteration。当你已经完成了第二个文件的迭代时。要回到开头,请使用fd.seek(0)

因为for lines in fd:将把读指针、文件指针或它调用的任何东西放在文件的末尾。在for循环之间调用fd.seek(0)

相关问题 更多 >

    热门问题