基于logi删除行

2024-10-03 13:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,其中有多个记录包含这些数据

F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89

现在我想搜索一行,如果我发现length<;=50,那么删除这行和文件中的下一行,然后写入另一个文件。在

谢谢大家


Tags: 文件数据lt记录lengthrankf00dy4302b8jrq
3条回答

假设Python2.6(如果您需要另一个版本,请告诉我们!),并且要跳过长度为<;=50的每一行(在每种情况下忽略下一行),如果有:

import re

def weirdtask(infname, oufname):
  inf = open(infname, 'r')
  ouf = open(oufname, 'w')
  rle = re.compile(r'length=\s*(\d+)')
  for line in inf:
    mo = re.search(line)
    if mo:
      thelen = int(mo.group(1))
      if thelen <= 50:
        next(inf)
        continue
    ouf.write(line)
  ouf.close()

如果这不完全是你的规格,请澄清。在

^{pr2}$

如果列总是以相同的顺序排列,并且总是有相同的编号,则只需对字符串使用.split()方法,然后使用索引找到所需的列:

words = line.split()
l = words[4]
temp = l.split("=")[2]
if int(temp) <= 50:
    # found the line, handle it
    do_something_here()

如果列可以按任何顺序排列,则可以使用正则表达式。在

^{pr2}$

它使用正则表达式中的“match group”来获取数字。在

当我写这篇文章时,出现了两个答案。我不是西方最快的枪。在

从我的头顶:

for every line in file
split by spaces
get last token
split by equal
verify length
write line to another file
delete line and the next

希望这就是你开始工作所需要的。在

相关问题 更多 >