无法写入文本文件和维护python格式

2024-09-29 17:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在保持格式的同时,我无法写入文本文件和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() 

Tags: ipforaddress格式statusokmethodinterface
1条回答
网友
1楼 · 发布于 2024-09-29 17:21:25

file对象的write()方法将作为参数传递的字符串写入文件,而不添加换行符(与例如print相反)。将数据拆分为行还将删除其中的换行符。你知道吗

因此,您需要显式添加换行符:

f = open("testtxt.txt",'ab')
for x in writethis.splitlines():
    f.write(x)
    f.write('\n')

或者,如果不修改for循环中的行,可以考虑一次将writethis写入文件。write()能够处理包含多行的相当大的字符串。你知道吗

相关问题 更多 >

    热门问题