使用python删除两个值之间的文本行

问题描述 投票:0回答:1

我需要运行一个 python 脚本,该脚本将删除两个可预测的注释块之间的文本块/行。

假设我有一个这样的文件

## Start of Part 1
Some text
Some more text
A bit more text
## End of Part 1

## Start of Part 2
Some text again
Some more text again
A bit more text again
## End of Part 2

我想删除

## Start of Part 1
## End of Part 1
之间的所有行,包括注释行

有没有办法用Python来做到这一点?

python-3.x
1个回答
0
投票

在命令行中传递文件名:

import sys
f = open(sys.argv[1], 'r')
skip = False
for line in f:
    line = line.rstrip()
    if line == '## Start of Part 1':
        skip = True
    if not skip:
        print(line)
    if line == '## End of Part 1':
        skip = False
© www.soinside.com 2019 - 2024. All rights reserved.