Python 3 - 尝试使用Cisco路由器部署脚本。 我试图在'router-input.txt'的输入值中替换多个文本值。不幸的是,我无法弄清楚如何在单个文件中替换多个值。在运行以下代码结束时,只输入最后一个值IOSOLD。
import fileinput
HOSTNAME = input("Hostname: ")
IOSCURRENT = input("Current IOS image: ")
IOSOLD = input("Old IOS image: ")
f = open("router-input.txt",'r')
filedata = f.read()
f.close()
newdata = filedata.replace("$HOSTNAME", HOSTNAME )
newdata = filedata.replace("$IOSCURRENT", IOSCURRENT )
newdata = filedata.replace("$IOSOLD", IOSOLD )
f = open('output.txt','w')
f.write(newdata)
f.close()
答案 0 :(得分:1)
您继续修改filedata
并将其保存在newdata
中。每次,您都会覆盖以前的更改。尝试:
newdata = filedata.replace("$HOSTNAME", HOSTNAME )
newdata = newdata.replace("$IOSCURRENT", IOSCURRENT )
newdata = newdata.replace("$IOSOLD", IOSOLD )
答案 1 :(得分:0)
如果文件太大,读取文件并将其保留在内存中效率非常低。我可能会做这样的事情
search_replace_dict = {
"$HOSTNAME": 'HOSTNAME',
"$IOSCURRENT": 'IOSCURRENT',
"$IOSOLD": 'IOSOLD'}
with open("router-input.txt") as input_file, open('output.txt','w') as output_file:
for each_line in input_file:
for key, value in search_replace_dict.items():
each_line = each_line.replace(key, value)
output_file.write(each_line)