I’m trying to use regex to find a specific file name in a folder, however it seems like my regex is not working.
Inside my folder the names of the excel files are
JavaScript
x
5
1
Payments - 2020-10-24.xlsx
2
Payments - 2020-10-25.xlsx
3
Payments - 2020-10-26.xlsx
4
Payments - 2020-10-27.xlsx
5
JavaScript
1
15
15
1
import re
2
import datetime
3
4
filepath = os.listdir("C:\Users\myUserName\Documents\folder")
5
date = today.strftime('%Y-%m-%d')
6
7
regex = fr'^Payments - {date}.xlsx$'
8
pattern = re.compile(regex)
9
10
for i in filepath:
11
if pattern.fullmatch == True:
12
print(i)
13
else:
14
print('No')
15
Advertisement
Answer
You are not testing your regex against anything. pattern.fullmatch
will return a method object. You probably wanted to write
JavaScript
1
2
1
if pattern.fullmatch(i):
2
That being said, I don’t see a reason to use a regex here. You can simply do
JavaScript
1
4
1
if i == f'Payments - {date}.xlsx':
2
print(i)
3
4
or even better (without checking all files in the folder):
JavaScript
1
6
1
from os import path
2
if path.exists(f"C:/<your folders>/Payments - {date}.xlsx"):
3
print("Found")
4
else:
5
print("Not found")
6