2017-12-04 3 views
0

正規表現を複数のファイルで実行することができました。この出力を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

への書き込みにprint機能にfileキーワード引数を使用します。 – kindall

答えて

0

我々だけで出力ファイルを開き、あなたは `pattern.subは()`の交換をしたいファイル

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) 
関連する問題