我有一个.txt文件,其结构如下:
name
parameter 1
parameter 2
parameter 3
\n
name2
p1
p2
p3
\n
(...)
我不知道如何创建一个从文件中删除块(名称,参数和\ n)的函数,该函数将名称作为函数参数。
答案 0 :(得分: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"
开头的块的新文件。它假定块用空行分隔。
答案 1 :(得分:0)
也许你可以使用readline: readline() from tutorialspoint或 this one is from python documentation about readline
答案 2 :(得分: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)