I want to check if all of the files (B01:B12) are present in a certain folder. If that is the case it should return True. I know the end of the filenames, but the beginning can vary.
Currently, I have the following code. It works, but I feel that it can be done a lot more efficient. Does anyone have an idea on how to improve this?
def Check3(filename, root):
path = os.path.join(root, filename)
os.chdir(path)
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('_B01.jp2'):
B01 = True
elif filename.endswith('_B02.jp2'):
B02 = True
elif filename.endswith('_B03.jp2'):
B03 = True
elif filename.endswith('_B04.jp2'):
B04 = True
elif filename.endswith('_B05.jp2'):
B05 = True
elif filename.endswith('_B06.jp2'):
B06 = True
elif filename.endswith('_B07.jp2'):
B07 = True
elif filename.endswith('_B08.jp2'):
B08 = True
elif filename.endswith('_B8A.jp2'):
B8A = True
elif filename.endswith('_B09.jp2'):
B09 = True
elif filename.endswith('_B10.jp2'):
B10 = True
elif filename.endswith('_B11.jp2'):
B11 = True
elif filename.endswith('_B12.jp2'):
B12 = True
return B01 and B02 and B03 and B04 and B05 and B06 and B07\
and B08 and B8A and B09 and B10 and B11 and B12
You can use
pathlibto get all files, extract last 8 characters from the file names, then build expected suffixes, compare lastly.The code firstly get all file names and suffixes, there could be more efficient ways that compares while globing.