I have a directory of text files. I need to set a status for each file based on whether it matches 1, both or neither regex patterns. My plan is:
- Walk directory
- If the file’s content:
- does not match either pattern, status = 1
- matches pattern1 BUT NOT pattern2, status = 2
- matches pattern2 BUT NOT pattern1, ignore
- matches pattern1 AND pattern2, status = 3
- Print file name and status
My code:
JavaScript
x
14
14
1
pattern1 = re.compile(r'critical', re.IGNORECASE)
2
pattern2 = re.compile(r'gouting bile', re.IGNORECASE)
3
4
for file in os.listdir('/home/ea/medical'):
5
if re.findall(pattern1, file) and re.findall(pattern2, file):
6
status = 3
7
print(file, "Status: ", status)
8
elsif re.findall(pattern1, file) and not re.findall(pattern2, file):
9
status = 2
10
print(file, "Status: ", status)
11
else:
12
status = 1
13
print(file, "Status: ", status)
14
My issue is that this doesn’t return anything.
Advertisement
Answer
you need to read the files, you’re just checking the patterns against the filenames.
JavaScript
1
9
1
for file in os.listdir('/home/ea/medical'):
2
contents = open(os.path.join('/home/ea/medical', file)).read()
3
status = 1
4
if re.search(pattern1, contents):
5
status += 1
6
if re.search(pattern2, contents):
7
status += 1
8
print(f"{file} Status: {status}")
9