Python for loop only goes through once -


i'm writing script search through multiple text files mac addresses in them find port associated with. need several hundred mac addresses. function runs first time through fine. after though new mac address doesn't passed function remains same 1 used , functions loop seems 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     switches in source_file:         countfor = countfor + 1         # print sneaky goes through loop once         switch = switches[4]         source_switch = open(switch + '.txt', 'r')         switch_read = source_switch.readlines()         mac in switch_read:             # print mac search through switches             found_mac = re.search(sneaky, mac)             if found_mac not none:                 interface = re.search("(gi|eth|te)(\s+)", mac)                 if interface not none:                     port = interface.group()                     macaddress.writerow([sneaky, switch, port])                     print sneaky + ' ' + switch + ' ' + port         source_switch.close()    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 not none:         sneaky = match.group()         find_mac(sneaky)         countmac = countmac + 1 print count print countmac print countfor 

i've added count countfor , countmac see how many times loops , functions run. here output.

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

any insight appreciated.

source_file opened globally once, first time execute call find_mac(), for switches in source_file: loop exhaust file. since file wasn't closed , reopened, next time find_mac() called file pointer @ end of file , reads nothing.

moving following beginning of find_mac should fix it:

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

consider using with statements ensure files closed well.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -