Reputation: 2287
I have a python script, with a nested for
loop
HostList = file('trylist.txt')
DestHostList = file('trylist2.txt')
for DestHost in DestHostList:
DestHost = DestHost.strip()
for HostName in HostList:
HostName = HostName.strip()
try:
if DestHost!=HostName:
print HostName,DestHost
print "one loop finishes"
except Exception, e:
ExceptionHost.write(HostName+' - '+DestHost+': '+str(e)+'\n')
print "exception"
#traceback.print_exc(file=sys.stdout)
The outer for
loop appears to be only executed once.
What could be the potential problem?
Upvotes: 2
Views: 4745
Reputation: 64368
The outer loop executes more than once, but only in the first iteration it has things to do. In the rest, the inner loop does not execute, leaving you with the impression it's only running once.
The problem is that you open the first file, trylist.txt
, and read it entirely in the first iteration of the outer loop. On the second iteration, the file object (which is iterator-like) has already been "consumed".
Try:
HostList = file('trylist.txt').readlines() # now it's a list of lines, not an iterator
DestHostList = file('trylist2.txt')
for DestHost in DestHostList:
DestHost = DestHost.strip()
for HostName in HostList:
If the file is huge and you want to avoid storing it in memory, you can reopen it every time:
DestHostList = file('trylist2.txt')
for DestHost in DestHostList:
DestHost = DestHost.strip()
HostList = file('trylist.txt')
for HostName in HostList:
Also, it is good practice to open files in python using a with
statement.
Upvotes: 4
Reputation: 4955
The problem is that you have exhausted the second file in the inner loop after the first pass.
As I can see you were trying to troubleshoot the issue with try ... except ...
. But since the file read operation is outside the block, you missed it.
Here is a solution with reading in advance all file content. I hope it will help:
host_list = file("trylist.txt").readlines()
dest_host_list = file("trylist2.txt").readlines()
for h in host_list:
for d in dest_host_list:
h,d = h.strip(),d.strip()
if h != d:
print h,d
Upvotes: 0