【问题标题】:Python save to file loopPython保存到文件循环
【发布时间】:2023-11-20 23:52:01
【问题描述】:

我需要一些帮助来为我的程序创建一个循环。我的问题是在文件/输出注册对我的配置所做的任何更改之前,我必须运行脚本两次。

编程不是我的强项——希望有人能提供帮助

更新代码:

try:
    rescue = cu.rescue(action="get", format="text")
    if rescue is None:
        print ("No existing rescue configuration.")
        print ("Saving rescue configuration.")
        cu.rescue(action="save")    
    else:
        print ("Rescue configuration exist:")
        print ("Updating rescue configuration")
        cu.rescue(action="save")
        print (rescue)
except Exception as err:
    print (err)

with open("Rescue Config.config", "w") as text_file:
text_file.write(rescue)

【问题讨论】:

  • 是否出现缩进错误?或者您粘贴了没有正确格式的代码?使用with 时无需关闭文件
  • 它只是在没有正确格式的情况下粘贴 - 好的,谢谢
  • 如果您要发布 Python 代码,请努力准确地重现您的缩进。如果读者必须尝试猜测您的实际缩进,他们可能会错过问题或在程序中引入新问题。

标签: python automation junos-automation


【解决方案1】:

缩进在python中很重要,将代码的最后几行改为这个

with open("Rescue Config.config", "w") as text_file:
     text_file.write(rescue)

无需关闭文件,使用with 语句时会自动发生这种情况

【讨论】: