How to run a script on all *.txt files in current directory?
python, regex
Solution
Use `glob.glob`:
import os, re
import glob
pattern = re.compile('word1(.*?)word3', flags=re.S)
for file in glob.glob('*.txt'):
with open(file) as fp:
for result in pattern.findall(fp.read()):
print result
Problem
I am trying to run below script on all *.txt files in current directory. Currently it will process only test.txt file and print block of text based on regular expression. What would be the quickest way of scanning current directory for *.txt files and running below script on all found *.txt files? Also how I could include lines containing 'word1' and 'word3' as currently script is printing only content between those two lines? I would like to print whole block. ``` #!/usr/bin/env python import os, re file = 'test.txt' with open(file) as fp: for result in re.findall('word1(.*?)word3', fp.read(), re.S): print result ``` I would appreciate any advice or suggestions on how to improve above code e.g. speed when running on large set of text files. Thank you.