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
Payments - 2020-10-24.xlsx Payments - 2020-10-25.xlsx Payments - 2020-10-26.xlsx Payments - 2020-10-27.xlsx
import re
import datetime
filepath = os.listdir("C:\Users\myUserName\Documents\folder")
date = today.strftime('%Y-%m-%d')
regex = fr'^Payments - {date}.xlsx$'
pattern = re.compile(regex)
for i in filepath:
if pattern.fullmatch == True:
print(i)
else:
print('No')
Advertisement
Answer
You are not testing your regex against anything. pattern.fullmatch will return a method object. You probably wanted to write
if pattern.fullmatch(i):
That being said, I don’t see a reason to use a regex here. You can simply do
if i == f'Payments - {date}.xlsx':
print(i)
...
or even better (without checking all files in the folder):
from os import path
if path.exists(f"C:/<your folders>/Payments - {date}.xlsx"):
print("Found")
else:
print("Not found")