[英]Removing a block of lines from a txt file
我有一个.txt文件,其结构如下:
name
parameter 1
parameter 2
parameter 3
\n
name2
p1
p2
p3
\n
(...)
我不知道如何制作从文件中删除块(名称,参数和\\ n)的函数,该文件将名称作为函数参数。
没有从文件中删除之类的事情。 您只能读写文件。 但是您可以在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"
开头的块。 假定块用空白行分隔。
也许您可以使用readline: 来自tutorialspoint的readline()或这是有关readline的python文档
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.