Update: How do I return a string from a regex match in python? - this question seems similar and I've updated accordingly.
I'm trying to open a file to write to it but, I don't know its case, so I'm trying to case-insensitive match its filename from its path.
Currently, with print(my_file)
, I see all the files in the folder_path
but, file_match
returns None. I also tried re.search instead of re.match and it returns None as well.
import re
from pathlib import Path as p
cwd = p.cwd()
folder_path = p(cwd / 'somefolder')
for my_file in folder_path.iterdir():
print(my_file)
file_match = re.search('.+/test.txt', str(my_file), re.IGNORECASE)
print(file_match) # Gives me <re.Match object; span=(0, 97), match='/the/path>
print(file_match) # gives me None
I'm hoping to match one of the following etc:
- /cwd/somefolder/test.txt
- /cwd/somefolder/TEst.Txt
- /cwd/SOMEFolder/teSt.TXT
but not this:
- /cwd/somefolder/NotTest.txt
- /cwd/somefolder/Other.mp3
Ultimately, I want a variable that includes the path to the /cwd/somefolder/test.txt, just in any case it happens to exist in. This way I can open and write to said file.
Here's the regular expression I'm using, which appears to be working: https://regex101.com/r/hz5qNe/2
Note: there is only one test.txt in each folder I'm searching in but, I don't know its case i.e. the filename is always the same but, the case can be different depending on the current folder_path iteration (I'm looping to find each folder's test.txt path but, didn't include that in the above code, as to par it down to its simplest form.)
Any help would be appreciated, thanks!