繁体   English   中英

我正在尝试编写 python 脚本以在文件中查找超过 1000 行的字符串,并在该字符串匹配后删除几行 (10)

[英]I am trying to write python script to find a string in file with more than 1000 lines and delete few lines (10) after that string match

在fastfile(超过1000行)下,我想搜索字符串“Validate repo test2”并删除从“Validate repo test2”开始到字符串“end”的行并将内容重写到新文件。

快速文件

desc "验证 repo test1"
车道 :validate_repo 做
lint_source
执行测试
验证文档
确保工具名称格式
确保代码样本
ensure_special_docs_code_samples
ensure_code_snippets
ensure_actions_config_items_formatting
结尾

desc "验证 repo test2"
车道 :validate_repo 做
lint_source
执行测试
验证文档
确保工具名称格式
确保代码样本
ensure_special_docs_code_samples
ensure_code_snippets
ensure_actions_config_items_formatting
结尾

desc "验证 repo test3"
车道 :validate_repo 做
lint_source
执行测试
验证文档
确保工具名称格式
确保代码样本
ensure_special_docs_code_samples
ensure_code_snippets
ensure_actions_config_items_formatting
结尾

你可以这样做:

with open('Fastfile', 'r') as f_orig, open('Fastfile_new', 'w') as f_new:
    skipping = False
    for line in f_orig:
        if 'Validate repo test2' in line:
            skipping = True
        if not skipping:
            f_new.write(line)
        if line[:3] == 'end':
            skipping = False

也许有很多解决方案,但我认为以下代码也可以解决您的问题。

need_delete = False
with open(path_to_old_file, 'r') as fin, open(path_to_new_file, 'w+') as fout :
    for line in fin:
        if line.endswith('"Validate repo test2"\n'):
            need_delete = True
        if need_delete and not line.strip():
            need_delete = False
            continue
        if not need_delete:
            fout.write(line)

我希望这能帮到您。

我是新手,所以我不知道如何归功于作者,但这对我很有用:正则表达式匹配两个字符串之间的所有字符谢谢@zx81

您可以使用正则表达式:

(?s)(?<="Validate repo test[\d]*").*(?=end)

http://www.rexegg.com/regex-modifiers.html#dotall第一部分将启用“点全模式”,正则表达式的其余部分表示“选择”之间的所有字符“验证回购测试[\\d]*” "和"结束""。 从那里您可以使用 regex sub 删除所有这些。 总之,它看起来有点像这样:

import re

fileText = file.read()
regex = re.compile(r"\"Validate repo test[\d]*\"", re.DOTALL)
result = re.sub(regex, "", fileText)

file.write(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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