繁体   English   中英

从txt文件中删除一行

[英]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文档

  1. 从源文件读取每一行。
  2. 如果该行包含函数参数(名称或其他内容),则继续(不读此行,跳至下一行)。
  3. 然后附加所有过滤的行以创建新文件。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM