为了账号安全,请及时绑定邮箱和手机立即绑定

删除现有文件的内容并重新写入内容

删除现有文件的内容并重新写入内容

江户川乱折腾 2022-06-28 17:20:22
专家,这个问题很常见,我已经尝试过基于 SO 中的解决方案和示例,但仍然无法将我所有的设备打印输出写入文件。我使用几种方法进行了测试,大多数时候我的文本文件中只有最后一行输出。下面的问题与我的几乎相同......但我没有运气。我测试脚本以根据设备类型运行特定命令。如果设备 A 运行命令 A,如果设备 B 运行命令 B,如果设备 C 运行命令 c。文本文件中的设备列表(列表有类型和 IP 地址)。当我使用“w”时,文件内容仅在最后一行,但当我使用“a”时,它将保存列表中所有设备的所有内容,但当我再次运行脚本时,它将继续写入最后一个指针和因此我得到了重复的内容..它追加并保持追加。使用 outFileName 时,"w" 输出内容只取最后一行内容OUTPUT CONTENT for device type C IP 10.2.10.12使用 outFileName 时,“a”输出内容第一次运行脚本如下OUTPUT CONTENT for device type A IP 192.168.100.100OUTPUT CONTENT for device type A IP 192.168.100.110OUTPUT CONTENT for device type B IP 10.1.10.100OUTPUT CONTENT for device type C IP 10.2.10.10OUTPUT CONTENT for device type C IP 10.2.10.11OUTPUT CONTENT for device type C IP 10.2.10.12第二次运行脚本时...文件包含重复项,如下所示OUTPUT CONTENT for device type A IP 192.168.100.100OUTPUT CONTENT for device type A IP 192.168.100.110OUTPUT CONTENT for device type B IP 10.1.10.100OUTPUT CONTENT for device type C IP 10.2.10.10OUTPUT CONTENT for device type C IP 10.2.10.11OUTPUT CONTENT for device type C IP 10.2.10.12OUTPUT CONTENT for device type A IP 192.168.100.100OUTPUT CONTENT for device type A IP 192.168.100.110OUTPUT CONTENT for device type B IP 10.1.10.100OUTPUT CONTENT for device type C IP 10.2.10.10OUTPUT CONTENT for device type C IP 10.2.10.11OUTPUT CONTENT for device type C IP 10.2.10.12脚本如下#Define functions for each device_typedef type_A(ip):    return{        'device_type': 'A',        'ip': ip,        'username': 'usr10',        'password': 'password',        }def type_B(ip):    return{        'device_type': 'B',        'ip': ip,        'username': 'usr10',        'password': 'password',        }def type_C(ip):    return{        'device_type': 'C',        'ip': ip,        'username': 'usr10',        'password': 'password',        }#Function to create output text filedef writeOutFile(outFileName, string):    with open(outFileName, "w") as f:       outfile = f.write(string)#Open Text file that contain device type and ip addressdeviceFile = open('devices.txt','r')
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

如果文件存在,以模式打开会'w'截断文件,而模式'a'将附加到它。

您的问题是您正在使用模式为每一行输出重新打开文件。'w' 每次重新打开文件时,都会破坏以前的内容。

这个问题有两种解决方案:

  1. 首选的解决方案是在脚本中打开文件一次并使用现有的文件句柄向其中写入多行,而不是为每一行输出打开一个新的文件句柄。

  2. 您也可以'w'在脚本开头使用模式打开文件一次,然后从那时起使用模式'a'(但这是一个 hack)。

实现第一个选项的一种方法是在主循环之前打开文件:

with open("outputFile.txt", "w") as f:

    for line in deviceFile:

        # ...


        # Replace this line:

        # writeOutFile(outFileName, sendCommand)

        # With this one:

        f.write(sendCommand)

您可能需要"\n"在写入该字符串之前添加一个换行符 ( );我看不出dvs_connect.send_command()它的输出是如何格式化的。


查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号