Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将循环的输出打印到单个文件Python_Python 3.x_Loops - Fatal编程技术网

Python 3.x 将循环的输出打印到单个文件Python

Python 3.x 将循环的输出打印到单个文件Python,python-3.x,loops,Python 3.x,Loops,我有以下代码: ipaddr = input("Enter IP Address: ") devicename = input ("Enter Device Name: ") for i, d in zip(ipaddr.split(), devicename.split()): print("Your IP is: ", i, "Your device is: ", d) 我的输出是: Enter IP Address: 1 2 3 4 5 Enter Device Name: d

我有以下代码:

ipaddr = input("Enter IP Address: ")
devicename = input ("Enter Device Name: ")

for i, d in zip(ipaddr.split(), devicename.split()):
   print("Your IP is: ", i, "Your device is: ", d)
我的输出是:

Enter IP Address: 1 2 3 4 5

Enter Device Name: d1 d2 d3 d4 d5

Your IP is:  1 Your device is:  d1
Your IP is:  2 Your device is:  d2
Your IP is:  3 Your device is:  d3
Your IP is:  4 Your device is:  d4
Your IP is:  5 Your device is:  d5
我希望上面的每一行(IP和设备名称组合)都保存到单独的txt文件中,如下所示:

C:\Scripts
d1.txt
d2.txt
d3.txt
d4.txt
d5.txt

我正在考虑创建另一个程序,以便在其他时间单独读取这些文件。目前,我正在研究将输出保存到不同的文件中。希望你能帮忙。谢谢大家!

实际上,您只需将文件创建添加到循环中,如下所示:

for i, d in zip(ipaddr.split(), devicename.split()):
     with open("d%d.txt"%i, "w") as fp:
          fp.write("Your IP is: ", i, "Your device is: ", d)

这将起作用,您可以使用以下语法在字符串中添加变量:

variable=33
a="%s"%variable
print(a)
输出将是:

'33'

ipaddr = input("Enter IP Address: ")
devicename = input ("Enter Device Name: ")

for i, d in zip(ipaddr.split(), devicename.split()):
   print("Your IP is: ", i, "Your device is: ", d)
   with open("%s.txt"%d,"w")as file: #opens a file with value of d.txt as file name to write
        file.write("Your IP is: %s Your device is %s"%(i,d))

这很有魅力,先生。正是我需要的。非常感谢你!