filter regex

Solutions on MaxInterview for filter regex by the best coders in the world

showing results for - "filter regex"
Angela
03 Jul 2018
1import os
2import re
3 
4def find_files(file_type):
5    os.chdir(path)
6    with os.scandir(path) as it:
7        for entry in it:
8            if entry.name.endswith(file_type) and entry.is_file():
9                yield entry.name
10 
11def find_in_file(files, pattern):
12    for file in files:
13        with open(file, encoding='utf-8') as f:
14            for index, line in enumerate(f, 1):
15                for match in re.finditer(pattern, line):
16                    print(f'Found <{line.strip()}> in file <{file}> on line <{index}>')
17 
18if __name__ == '__main__':
19    path = r'E:\div_code\new\cat_pic'
20    pattern = re.compile(r'cat|dog\d\d(?!\d)')
21    file_type = '.txt'
22    files = find_files(file_type)
23    find_in_file(files, pattern)
24