[英]Python remove all lines starting with pattern
所以我有 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
作为 output 我想要:
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()
但是上例的 output 是:
2 0.71 0.47 0.96
如何修复代码以给我正确的 output?
这是因为您在 for 循环中覆盖了 output。 您可以保存到不同的文件:
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()
问题是您正在重新初始化每一行的 output 文件。 这可以通过提前打开 output 文件并将其用于每一行来解决。
#!/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')
)
错误在这里:
open(filename, 'w')
这将覆盖循环的每次迭代,因此您只会获得最后一个条目。
open(filename, 'a')
这a
追加内容。 但更好的是在循环之外只打开一次输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.