我有此代码:
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
我正在考虑创建另一个程序以在其他时间单独读取这些文件。目前,我正在考虑将输出保存到其他文件中。希望您能提供帮助。谢谢!
答案 0 :(得分:1)
这将起作用,您可以使用以下语法在字符串中添加变量:
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))
答案 1 :(得分:0)
您实际上需要添加的就是在循环中创建文件,如下所示:
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)