2013-02-25 199 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"块。它假定块以空行分隔。