2017-10-28 90 views
1

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

我到处都在网上搜索,但我似乎无法找到一个优雅的解决方案。以下是我想要实现的一个例子。

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 

回答

1

如果文本文件非常庞大,就像您说的那样,您会希望避免使用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 
+0

我最终使用了这个。我不需要在特定情况下使用正则表达式,所以我不打算使用re模块。此外,由于print语句引发了以下警告,我将'print(line,file = output_fh)'更改为output_fh.write(line):预期类型'Optional [IO [str]]',改为'TextIOWrapper [str]' 。 谢谢大家的支持! – jmm5351

1

您可以使用下面的正则表达式来实现这一目标:

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

现场演示here

可以搭配使用上述正则表达式然后替换为空字符串(''

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

CODE

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 
+0

如果遇到字符串“BEGIN123”会怎么样? – ailin

+0

已更新,谢谢 –

0

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

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'将所有内容都读入内存,但可以逐行读取更多内容 - 也应该更加精简内存。

相关问题