[英]looping regex in directory and saving output
I was able to run the regex on multiple files, I want to save the output of this like name_of_file_clean.txt
. 我能够在多个文件上运行正则表达式,我想保存此输出,例如
name_of_file_clean.txt
。
Trying to find the best way. 试图找到最好的方法。
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)
We'll just open the output file and use the print
functions file
keyword argument to write to the file 我们只需要打开输出文件,然后使用
print
functions 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.