2017-06-07 32 views
1

好,我有以下代碼:添加行

numList = [6, 7, 8, 10, 15, 18, 31, 35, 51, 54] 

with open('/home/user/test.nft') as f: 
    lines = f.readlines() 

for i, l in enumerate(lines): 
    for num in numList: 
     if l.startswith('add rule ip filter vlan_%d' %num): 
      if "oifname bond1.%d" %num in l: 
       f = open('inet-filter-chain-vlan%d_in.nft' %num, 'a') 
      else: 
       f = open('inet-filter-chain-vlan%d_out.nft' %num, 'a') 

      f.write(l) 
      f.close() 
      break 

我想在生成文件的開頭和結尾中,如果添加一行:INET -filter鏈-VLAN%d_in.nft和INET濾波器鏈-VLAN%d_out.nft。

例如,INET濾波器鏈vlan20_in.nft文件的內容應該是:對文件20

......內容

定製線.... .......

文件20

回答

0

需要緩存哪些文件被寫入到自定義線。

這可以用一組簡單的方式來完成,

爲什麼不能再次使用with open(...) as f:嗎?

fileset = set() 
for i, l in enumerate(lines): 
    for num in numList: 
     if l.startswith('add rule ip filter vlan_%d' %num): 
      in_out = 'in' if "oifname bond1.%d" %num in l else 'out' 
      filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out) 
      with open(filename, 'a') as f: 
       # the first time we open a file, output the custom line 
       if filename not in fileset: 
        custom_string="Custom line for %s\n" % filename 
        f.write(custom_string) 
        fileset.add(filename) 
       f.write(l) 
      break 
# now we need to write the final line in each file 
for filename in fileset: 
    with open(filename, 'a') as f: 
     custom_string="Custom line for %s\n" % filename 
     f.write(custom_string) 

還有其他的方法可以做到這一點,但是這很簡單,不會留下文件打開,裏面有開口的開銷,經常關閉文件(每行),但不開放的潛在許多文件。

如果你想保持打開的文件寫入服務表現,我建議使用裸打開後,使用一個字典(按文件名鍵)來存儲文件引用,然後寫在最後一行後關閉它們。它應該看起來像這樣:

filedict = {} 
for i, l in enumerate(lines): 
    for num in numList: 
     if l.startswith('add rule ip filter vlan_%d' %num): 
      in_out = 'in' if "oifname bond1.%d" %num in l else 'out' 
      filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out) 
       # the first time we open a file, output the custom line 
       f = filedict.get(filename) 
       if f is None: 
        custom_string="Custom line for %s\n" % filename 
        f = open(filename, 'a') 
        f.write(custom_string) 
        filedict[filename] = f 
       f.write(l) 
      break 
# now we need to write the final line in each file 
for filename, f in filedict: 
    custom_string="Custom line for %s\n" % filename 
    f.write(custom_string) 
    f.close() 
+0

感謝您的幫助,但我執行它,個性化的行被打印在文件的所有行。 – trick15f

+0

哦,我看到,在這種情況下,你希望緩存你是否訪問的文件,然後將它寫出來,當你關閉它。這是更多的工作:) – Baldrickk

+0

@ trick15f更新,以做到這一點。這個版本寫入的文件名,數量不限,這樣很容易得做,但我留給你。 – Baldrickk