遍历文件

时间:2019-02-20 01:25:09

标签: python regex loops

我想遍历文件并删除一系列与给定正则表达式匹配的行。我有下面的脚本,但它只删除了第一个匹配的行/正则表达式。我如何遍历文件才能使其正常工作?

import glob
import re

read_files = glob.glob("*.agr")

with open("out.txt", "w") as outfile:
for f in read_files:
    with open(f, "r") as infile:
        outfile.write(infile.read())


with open("out.txt", "r") as file:
    filedata = file.read()
    filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', '', filedata)
with open("out.txt", "w") as file:
    file.write(filedata)

谢谢

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,我需要修改正则表达式以指定> = 1位数字,如下所示:#time \ s + residue \ s + [0-9] + \ s + Total。以前,正则表达式中没有+号。