在保持格式的同时,我无法写入文本文件和python。你知道吗
这是我的密码。我想写一个文本文件,并保持这种精确的格式,但它把所有的文本放在一行。你知道吗
我尝试了很多方法来实现这一点,比如使用for循环、splitlines等
任何帮助都将不胜感激,谢谢。你知道吗
python 2.7.13版
writethis = """
192.168.4.4
Interface IP-Address OK? Method Status Protocol
FastEthernet0/0 192.168.4.4 YES NVRAM up up
FastEthernet0/1 192.168.44.135 YES manual up up
FastEthernet1/0 unassigned YES NVRAM administratively down down
192.168.4.2
Interface IP-Address OK? Method Status Protocol
FastEthernet0/0 192.168.4.2 YES NVRAM up up
FastEthernet0/1 192.168.2.2 YES NVRAM up up
FastEthernet1/0 192.168.3.2 YES NVRAM up up
"""
f = open("testtxt.txt",'ab')
for x in writethis.splitlines():
f.write(x)
f.close()
file对象的
write()
方法将作为参数传递的字符串写入文件,而不添加换行符(与例如print
相反)。将数据拆分为行还将删除其中的换行符。你知道吗因此,您需要显式添加换行符:
或者,如果不修改for循环中的行,可以考虑一次将
writethis
写入文件。write()
能够处理包含多行的相当大的字符串。你知道吗相关问题 更多 >
编程相关推荐