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 :(
3 Answers 3
I think the problem is that when you iterate the actual file it moves the cursor or something, so when you iterate it again you're at the end of file.
However, using .readlines() after every open() solves it (maybe because you don't iterate over the file itself but over a list created from it).
commandsfile = input ("Please Enter CommandsFile path as c:/example/ \n :")
hostsfile = input ("Please Enter Hosts path as c:/example/ \n :")
commands1 = open( (commandsfile), "r").readlines()
hosts = open((hostsfile) , "r").readlines()
for host in hosts:
print ("1")
for cmd in commands1:
print ("2 ")
If you want to iterate over the actual file, you can use seek() to change cursor position
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 ")
commands1.seek(0, 0)
1 Comment
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
Your commands1 is exhausted in the first iteration of the for loop.
When you do commands1 = open( (commandsfile), "r") you get an iterator in commands1 and will be exhausted in the for loop. You can convert the commamds1 iterator to a list by doing commamds1 = list(commamds1)
commandsfile = input ("Please Enter CommandsFile path as c:/example/ \n :")
hostsfile = input ("Please Enter Hosts path as c:/example/ \n :")
commands1 = open( (commandsfile), "r")
commands1 = list(commands1)
hosts = open((hostsfile) , "r")
for host in hosts:
print ("1")
for cmd in commands1:
print ("2 ")
print("2 ")to be within the second for loop? It would also help to provide verbatim copies of your two files since they seem to be short. The question as you asked it is a little confusing.seek(). See my answer