我能够在多个文件上运行正则表达式,我希望将此输出保存为name_of_file_clean.txt
。
试图找到最好的方法。
import os, re
import glob
pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
with open(file) as fp:
for result in pattern.findall(fp.read()):
print(result)
答案 0 :(得分:0)
我们只是打开输出文件并使用print
函数file
关键字参数写入文件
import os, re
import glob
pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
with open(file) as fp:
with open(file[:-4] + '_clean.txt', 'w') as outfile:
for result in pattern.findall(fp.read()):
print(result, file=outfile)