簡體   English   中英

Python 換行寫入文件

[英]Python write file in newline

    #1 
for line in matched_lines[0:2]:
    #2       
print (line) 
    
    #3        
file = open("pythonsnmp.txt", "w")
    #4        
x = str(matched_lines[0:2])
    #5        
file.write(x)
    #6        
file.write('\n')
    #7        
file.close()

在#2 中,結果是:

(146, '[interfaces.ifTable.ifEntry.ifDescr.8],(STRING),HPE Ethernet 1Gb 2-port 361T Adapter #2')
(162, '[interfaces.ifTable.ifEntry.ifDescr.24],(STRING),HPE Ethernet 1Gb 2-port 361T Adapter')

但是在txt文件中結果是:

[(146, '[interfaces.ifTable.ifEntry.ifDescr.8],(STRING),HPE Ethernet 1Gb 2-port 361T Adapter #2'), (162, '[interfaces.ifTable.ifEntry.ifDescr.24],(STRING),HPE Ethernet 1Gb 2-port 361T Adapter')]>

如果我想要與#2 相同的 txt 文件,我該如何編碼?

您可以將切片解壓縮為 arguments 以調用print function,它有一個關鍵字參數file ,指定要寫入的文件 stream:

with open("pythonsnmp.txt", "w") as file:
    print(*matched_lines[0:2], file=file, sep='\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM