我一直在努力使用Python來執行條件附加/擴展特定文本的文本文件。我很抱歉,如果這太基本了,並且已經在這裏討論過或者其他:(Python中的條件添加
關於代碼(附件),我只需要在包含「description」的語句下添加語句「mtu 1546」它不存在。另外,我希望能夠在界面語句(和/或上面的mtu語句,如果有的話)下添加「description TEST」語句,只要不存在,我就使用python 2.7。
這裏是我的代碼:
import re
f = open('/TESTFOLDER/TEST.txt','r')
interfaces=re.findall(r'(^interface Vlan[\d+].*\n.+?\n!)',f.read(),re.DOTALL|re.MULTILINE)
for i in interfaces:
interfaceslist = i.split("!")
for i in interfaceslist:
if "mtu" not in i:
print i
f.close()
print語句工作正常的情況,因爲它是能夠正確打印有趣的線,但是我的要求是添加(追加/擴展)所需的語句到列表中,以便我可以進一步使用它來解析和東西。在嘗試附加/擴展功能時,解釋器會將其視爲字符串對象。以下是示例源文件(文本)。我將解析的文本文件的大小很大,所以只添加有趣的文本。
!
interface Vlan2268
description SNMA_Lovetch_mgmt
mtu 1546
no ip address
xconnect 22.93.94.56 2268 encapsulation mpls
!
interface Vlan2269
description SNMA_Targoviste_mgmt
mtu 1546
no ip address
xconnect 22.93.94.90 2269 encapsulation mpls
!
interface Vlan2272
mtu 1546
no ip address
xconnect 22.93.94.72 2272 encapsulation mpls
!
interface Vlan2282
description SNMA_Ruse_mgmt
no ip address
xconnect 22.93.94.38 2282 encapsulation mpls
!
interface Vlan2284
mtu 1546
no ip address
xconnect vfi SNMA_Razgrad_mgmt
!
interface Vlan2286
description mgmt_SNMA_Rs
no ip address
xconnect 22.93.94.86 2286 encapsulation mpls
!
interface Vlan2292
description SNMA_Vraca_mgmt
mtu 1546
no ip address
xconnect 22.93.94.60 2292 encapsulation mpls
!
你有沒有注意到,你使用變量i在這兩個for循環? :) –
實際上,Python知道它是一個不同的變量,但是對於人類的讀者來說,它是令人困惑的。 –
謝謝邁克爾。這也正是我的想法.. – user531942