【问题标题】:Python remove all lines starting with patternPython删除所有以模式开头的行
【发布时间】:2021-01-18 18:18:42
【问题描述】:

所以我有 7000 多个 txt 文件,看起来像这样:

1 0.51 0.73 0.81

0 0.24 0.31 0.18

2 0.71 0.47 0.96

1 0.15 0.25 0.48

作为我想要的输出:

0 0.24 0.31 0.18

2 0.71 0.47 0.96

我编写的代码结合了多个来源,它看起来像这样:

    #!/usr/bin/env python3
  2 import glob
  3 import os
  4 import pathlib
  5 import re
  6 path = './*.txt'
  7 
  8 for filename in glob.glob(path):
  9     with open(filename, 'r') as f:
 10         for line in f.readlines():
 13             if not (line.startswith('1')):
 14                 print(line)
 15                 out = open(filename, 'w')
 16                 out.write(line)
 17         f.close()

但上例的输出是:

2 0.71 0.47 0.96

如何修复代码以提供正确的输出?

【问题讨论】:

  • 您在循环中使用w 打开文件,每次都会截断文件,只剩下最后一行。要么更改为a,要么在循环外打开一次
  • 你也永远不会关闭out,也没有理由关闭f,因为它是用上下文管理器打开的

标签: python python-3.x glob


【解决方案1】:

这是因为您覆盖了 for 循环中的输出。您可以保存到其他文件:

path = 'test.txt'
output = 'out.txt'
for filename in glob.glob(path):
    
    with open(filename, 'r') as f:
        out = open(outfile, 'w')
        for line in f.readlines():
            
            if not (line.startswith('1')):
                print(line)
                out.write(line)
        f.close()

或者您可以使用 append 创建一个数组,然后将其写入同一个文件:

import glob
import os
import pathlib
import re

path = 'test.txt'
output = []
for filename in glob.glob(path):
    
    with open(filename, 'r') as f:
        for line in f.readlines():
            if not (line.startswith('1')):
                print(line)
                output.append(line)
            
        with open(path, 'w') as w:
            for line in output:
                print(line)
                w.write(line)
        f.close()

【讨论】:

    【解决方案2】:

    问题是您正在重新初始化每一行的输出文件。这可以通过提前打开输出文件并将其用于每一行来解决。

    #!/usr/bin/env python3
    from glob import glob
    import os
    import pathlib
    import re
    
    for filename in glob('./*.txt'):
        with open(filename,'r') as original_file:
            original_lines=original_file.readlines()
        with open(filename,'w') as updated_file:
            updated_file.writelines(
                line
                for line in original_lines
                if not line.startswith('1')
            )
    

    【讨论】:

      【解决方案3】:

      错误在这里:

      open(filename, 'w')
      

      这将覆盖循环的每次迭代,因此您只能获得最后一个条目。

      open(filename, 'a')
      

      这将a追加内容。但更好的是在循环之外只打开一次输出文件。

      【讨论】:

        猜你喜欢
        • 2015-01-18
        • 2021-01-08
        • 1970-01-01
        • 2014-11-30
        • 1970-01-01
        • 2012-01-02
        • 2014-05-07
        • 1970-01-01
        相关资源
        最近更新 更多