2013-02-25 31 views
0

我有具有這樣的結構的.txt文件:從一個txt文件中刪除線的塊

name 
parameter 1 
parameter 2 
parameter 3 
\n 
name2 
p1 
p2 
p3 
\n 
(...) 

我不知道如何使刪除塊的功能(名稱,參數和\ n)從一個文件中獲得名稱作爲函數參數。

回答

0
def rmblock(path, block):       
    lines = open(path).readlines()     
    blockstart = lines.index(block + "\n")   
    blockend = lines.index(r"\n" + "\n", blockstart) 
    del(lines[blockstart:blockend+1])    
    open(path, 'w+').writelines(lines)    
+0

感謝幫助,但並沒有exacly工作。但blockend不必使用,因爲每個塊都有相同數量的參數,所以我用: del(lines [blockstart:blockstart + 5]) – Cragmorton 2013-02-25 11:51:13

0

有沒有這樣的事情從文件中刪除。您只能讀取和寫入文件。但是你可以從Python中刪除列表中的項目,或者在迭代忽略它們:

In [1]: def exclude(f, name): 
    ...:  with open(f) as fo: 
    ...:   found = False 
    ...:   for line in fo: 
    ...:    if line.strip() == name: 
    ...:     found = True 
    ...:     continue 
    ...:    if found and not line.strip(): 
    ...:     found = False 
    ...:    if not found: 
    ...:     yield line 
    ...: 

In [2]: with open('/tmp/new.txt', 'w') as new: 
    ...:  new.writelines(exclude('/tmp/text.txt', 'name')) 
    ...: 

這個例子寫一個新的文件,而無需啓動與"name"塊。它假定塊以空行分隔。