Python中嵌套For循环问题

时间:2016-06-18 20:51:05

标签: python loops for-loop nested

我是蟒蛇区的新手;我试图写一个简单的程序在多个设备上运行多个命令,从2个不同的文本文件输入,但输出有点奇怪,我不知道是什么问题 示例代码如下:

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 ")

我在hosts.txt中保存了2个设备 " AA" " BB" 和command.txt中保存的2个命令 " 11" " 22"

上面代码的输出是 1 2 2 1

我多么期待 1 2 2 1 2 2

任何建议如何解决:(

3 个答案:

答案 0 :(得分:1)

我认为问题在于当你迭代实际文件时会移动光标或其他东西,所以当你再次迭代它时,你就在文件的末尾。
但是,在每个s3cmd -e -v put --recursive --dry-run /Users/$USERNAME/Downloads/ s3://dgtrtrtgth777 INFO: Compiling list of local files... INFO: Running stat() and reading/calculating MD5 values on 15957 files, this may take some time... INFO: [1000/15957] INFO: [2000/15957] INFO: [3000/15957] INFO: [4000/15957] INFO: [5000/15957] INFO: [6000/15957] INFO: [7000/15957] INFO: [8000/15957] INFO: [9000/15957] INFO: [10000/15957] INFO: [11000/15957] INFO: [12000/15957] INFO: [13000/15957] INFO: [14000/15957] INFO: [15000/15957] 之后使用.readlines()解决它(可能是因为您没有遍历文件本身,而是遍历从其创建的列表)。

open()

如果要迭代实际文件,可以使用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 ") 更改光标位置

seek()

答案 1 :(得分:0)

一个简单快捷的解决方法是将commands行移到第一个循环中:

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

答案 2 :(得分:0)

你的命令1在for循环的第一次迭代中耗尽。 当你执行commands1 = open( (commandsfile), "r")时,你会在commands1中获得一个迭代器,并在for循环中耗尽。您可以通过执行commamds1 = list(commamds1)

将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 ")