I am using pathlib.Path()
to check whether a file exists, and open it as an image using rasterio.
filename = pathlib.Path("./my_file-name.tif")
However, some of the files in the directory I am loading from have a slightly different filename, e.g. my_filename.tif
(without a hyphen) or my_file_name.tif
(with an underscore instead of a hyphen).
All file names have the same basic structure. Is there a better way to call pathlib.Path()
with all possible variations in filename.tif
than just checking if they all exist? e.g.,
filename = pathlib.Path("./my_file-name.tif")
if not file.is_file():
file = Path("./my_file_name.tif")
if not file.is_file():
file = Path("./my_filename.tif")
You could use a regular expression (or expressions) to see if any files in your directory match. But you could also just check to see if a filename has all the necessary components. Here's an example you can adapt:
dir = pathlib.Path("./")
must_contain = ['my', 'file', 'name', '.tif']
true_filepath = None
for filepath in os.listdir(dir):
if all([item in filepath for item in must_contain]):
true_filepath = filepath
break
This will select the first item that contains all the necessary components. If you have specific requirements for the form that the components must take, then I'd suggest the regular expression route, where you use a regular expression(s) that match what you need. here's the documentation for the regular expression package re in python 3.
Hope this helps, Happy Coding!