【问题标题】:Nested For Loop Issue in PythonPython中的嵌套For循环问题
【发布时间】:2016-06-18 20:51:05
【问题描述】:

我是python领域的新手;我试图编写一个简单的程序来在多个设备上运行多个命令,输入来自 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 台设备 “啊” “bb” 以及保存在 commands.txt 中的 2 个命令 “11” “22”

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

我是怎么期待的 1 2 2 1 2 2

任何建议如何解决:(

【问题讨论】:

  • 您是否打算让print("2 ") 在第二个 for 循环中?这也将有助于提供您的两个文件的逐字副本,因为它们似乎很短。你问的问题有点令人困惑。
  • 问题是你正在读取一个文件,所以在第二个循环中,当你再次执行 for 时,文件指针不会回到开头
  • @aquiles ;有没有办法解决这个问题??
  • 是的,使用seek()。看我的回答

标签: python loops for-loop nested


【解决方案1】:

我认为问题在于,当你迭代实际文件时,它会移动光标或其他东西,所以当你再次迭代它时,你就在文件的末尾。
但是,在每个 open() 解决它之后使用 .readlines() (可能是因为您不遍历文件本身,而是遍历从它创建的列表)。

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() 更改光标位置

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)

【讨论】:

  • 乐于帮助...为什么不批准?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您的 commands1 在 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 ")
    

    【讨论】:

    • 我没有尝试过,但我相信这也能解决问题......非常感谢
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多