【问题标题】:Python 3+, Read In Text File and Write to New File Excluding Range of LinesPython 3+,读入文本文件并写入不包括行范围的新文件
【发布时间】:2017-10-28 17:58:13
【问题描述】:

我在 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  

【问题讨论】:

    标签: python text readfile writefile


    【解决方案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
    

    【讨论】:

    • 我最终使用了这个。在我的特定情况下,我不需要使用正则表达式,所以我不会使用 re 模块。此外,我将 'print(line, file=output_fh)' 更改为 output_fh.write(line),因为 print 语句引发了以下警告: Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead .谢谢大家的支持!
    【解决方案2】:

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

    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
    

    【讨论】:

    • 遇到"BEGIN123"这样的字符串怎么办?
    【解决方案3】:

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

    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'将所有内容读入内存,而是采用更多的逐行方法 - 这也应该更精简内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2023-03-13
      • 2018-08-07
      • 1970-01-01
      相关资源
      最近更新 更多