在维护格式时,我在写入文本文件和python时遇到了问题。
这是我的代码。我想写入一个文本文件并保持这种格式,但它将所有文本放在一行上。
我尝试了许多方法,比如使用for循环、拆分行等
任何帮助都将不胜感激,谢谢。
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()
发布于 2018-07-11 03:17:26
文件对象的write()
方法将字符串作为参数写入文件,而不添加换行符(与print
不同)。将数据拆分成行也会删除其中的换行符。
因此,您需要显式添加一个换行符:
f = open("testtxt.txt",'ab')
for x in writethis.splitlines():
f.write(x)
f.write('\n')
或者,如果不修改for循环中的行,可以考虑将writethis
一次全部写入文件。write()
能够处理包含多行的非常大的字符串。
https://stackoverflow.com/questions/51272443
复制相似问题