【发布时间】: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