Saadi381 Saadi381 - 5 months ago 10
Python Question

Nested For Loop Issue in Python

I am a newbie in python area ; i was trying to write a simple program to run multiple commands on multiple devices , Input from 2 different text files but the output is a bit wierd and i am not sure what is the issue
sample code as below:

commandsfile = input ("Please Enter CommandsFile path as c:/example/ \n :")
hostsfile = input ("Please Enter Hosts path as c:/example/ \n :")
commands1 = open( (commandsfile), "r")
hosts = open((hostsfile) , "r")
for host in hosts:
print ("1")
for cmd in commands1:
print ("2 ")


i have 2 devices saved in hosts.txt
"aa"
"bb"
and 2 commands saved in commands.txt
"11"
"22"

the output for above code is
1
2
2
1

how ever i was expecting
1
2
2
1
2
2

any advice how to fix :(

Answer

An easy and quick fix would be to move the commands line into the first loop:

hosts = open((hostsfile) , "r")
for host  in hosts:
    print("1") 
    commands1 = open((commandsfile), "r")
    for cmd in commands1:
        print("2")
Comments