rdrash74
rdrash74

Reputation: 1

Python for loop only goes through once

I'm writing a script to search through multiple text files with mac addresses in them to find what port they are associated with. I need to do this for several hundred mac addresses. The function runs the first time through fine. After that though the new mac address doesn't get passed to the function it remains as the same one it already used and the functions for loop only seems to run once.

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

I've added the count countFor and countMac to see how many times the loops and functions run. Here is the output.

549f.3507.7674 the name of the switch Eth100/1/11 677 677 353

Any insight would be appreciated.

Upvotes: 0

Views: 538

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177650

source_file is opened globally only once, so the first time you execute call find_mac(), the for switches in source_file: loop will exhaust the file. Since the file wasn't closed and reopened, the next time find_mac() is called the file pointer is at the end of the file and reads nothing.

Moving the following to the beginning of find_mac should fix it:

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

Consider using with statements to ensure your files are closed as well.

Upvotes: 2

Related Questions