Python for循环只经过一次

时间:2016-07-25 21:21:15

标签: python python-2.7

我正在编写脚本来搜索其中包含mac地址的多个文本文件,以查找与之关联的端口。我需要为几百个mac地址执行此操作。该功能第一次运行正常。在此之后,尽管新的mac地址没有传递给函数,但它仍然与它已经使用的相同,并且循环函数似乎只运行一次。

import re
import csv

f = open('all_switches.csv','U')
source_file = csv.reader(f)

m = open('macaddress.csv','wb')
macaddress = csv.writer(m)

s = open('test.txt','r')
source_mac = s.read().splitlines()
count = 0
countMac = 0
countFor = 0
def find_mac(sneaky):
    global count
    global countFor
    count = count +1
    for switches in source_file:
        countFor = countFor + 1
        # print sneaky only goes through the loop once
        switch = switches[4]
        source_switch = open(switch + '.txt', 'r')
        switch_read = source_switch.readlines()
        for mac in switch_read:
            # print mac does search through all the switches
            found_mac = re.search(sneaky, mac)
            if found_mac is not None:
                interface = re.search("(Gi|Eth|Te)(\S+)", mac)
                if interface is not None:
                    port = interface.group()
                    macaddress.writerow([sneaky, switch, port])
                    print sneaky + ' ' + switch + ' ' + port
        source_switch.close()



for macs in source_mac:
    match = re.search(r'[a-fA-F0-9]{4}[.][a-fA-F0-9]{4}[.][a-fA-F0-9]{4}', macs)
    if match is not None:
        sneaky = match.group()
        find_mac(sneaky)
        countMac = countMac + 1
print count
print countMac
print countFor

我已经添加了count count和countMac来查看循环和函数运行的次数。这是输出。

549f.3507.7674交换机Eth100 / 1/11的名称 677 677 353

任何见解都将受到赞赏。

1 个答案:

答案 0 :(得分:2)

source_file仅在全局打开一次,因此第一次执行调用find_mac()时,for switches in source_file:循环将耗尽该文件。由于文件未关闭并重新打开,因此下次调用find_mac()时,文件指针位于文件的末尾,不会读取任何内容。

将以下内容移至find_mac的开头应该修复它:

f = open('all_switches.csv','U')
source_file = csv.reader(f)

考虑使用with语句来确保您的文件也已关闭。