Python 3+,读入文本文件并写入不包括行范围的新文件

Python 3+, Read In Text File and Write to New File Excluding Range of Lines

我在 Windows 机器上使用 Python 版本 3.6。我正在使用 open()readlines() 读取文本文件。读取文本文件行后,我想将某些行写入新的文本文件,但排除某些行范围。我不知道要排除的行的行号。文本文件很大,要排除的行范围因我正在阅读的文本文件而异。我可以搜索已知关键字以找到要从我要写入的文本文件中排除的范围的开始和结束。

我在网上到处搜索,但我似乎无法找到有效的优雅解决方案。以下是我正在努力实现的示例。

a  
b  
BEGIN  
c  
d  
e  
END  
f  
g  
h  
i  
j  
BEGIN  
k  
l  
m  
n  
o  
p  
q  
END  
r  
s  
t  
u  
v  
BEGIN  
w  
x  
y  
END  
z 

综上所述,我想把上面的内容读成Python。之后,写入一个新文件,但排除所有从 BEGIN 关键字开始到 END 关键字结束的行。

新文件应包含以下内容:

a  
b  
f  
g  
h  
i  
j  
r  
s  
t  
u  
v  
z  

您可以使用以下正则表达式来实现此目的:

regex = r"(\bBEGIN\b([\w\n]*?)\bEND\b\n)"

现场演示here

您可以使用上面的正则表达式进行匹配,然后替换为空字符串 ('')

Here's Python 中的一个工作示例。

代码

result = re.sub(regex, '', test_str, 0) # test_str is your file's content
>>> print(result)
>>> 
a
b
f
g
h
i
j
r
s
t
u
v
z

你有没有尝试过这样的事情:

with open("<readfile>") as read_file:
    with open("<savefile>", "w") as write_file:
        currently_skipping = False
        for line in read_file:
            if line == "BEGIN":
                currently_skipping = True
            else if line == "END":
                currently_skipping = False

            if currently_skipping:
                continue

            write_file.write(line)

这应该基本上完成了您需要做的事情。 基本上不要通过 'readlines' 将所有内容读入内存,而是采用更多的逐行方法 - 这也应该更适合内存。

如果文本文件很大,如您所说,您将希望避免使用 readlines(),因为这会将整个文件加载到内存中。相反,逐行阅读并使用状态变量来控制您是否处于应抑制输出的块中。有点像,

import re

begin_re = re.compile("^BEGIN.*$")
end_re = re.compile("^END.*$")
should_write = True

with open("input.txt") as input_fh:
    with open("output.txt", "w", encoding="UTF-8") as output_fh:
        for line in input_fh:
            # Strip off whitespace: we'll add our own newline
            # in the print statement
            line = line.strip()

            if begin_re.match(line):
                should_write = False
            if should_write:
                print(line, file=output_fh)
            if end_re.match(line):
                should_write = True