I need to iterate through different folders and check if certain files are present inside directory based on their file extensions.
However during iteration it is also checking on the subfolders present inside the main folder and checking if files are present inside the sub-folder. How to avoid this search?
file_format = (".xlsx", ".txt", ".png")
files_path = "D:\\Tools\\Results"
for subdir, dirs, files in os.walk(files_path):
matching_files = [file for file in files if file.endswith(file_format)]
if len(matching_files) > 0:
print(f"\nFiles are present in '{subdir}'")
for file_name in matching_files:
print(f"{file_name} - Latest file available")
else:
print(f"{file_name} - Latest file not available")
Inside Results, I have two folders: Test_Results_1 and Test_Results_2. I want to check for files ending with file extensions only in these two folders. Suppose if there are folders with any name inside Test_Results_1 and Test_Results_2, it should not enter into those folders and perform the check
Tried to compare with subdir, but only the first folder is taken into consideration Only the results from Test_Results_1 are updated. The results for Test_Results_2 folder are not displayed
for subdir, dirs, files in os.walk(sw_files_path):
matching_files = [file for file in files if file.endswith(file_format)]
if subdir.lower().endswith(now+"\Test_Results_1"):
if len(matching_files) > 0:
print(f"\nFiles are present in '{subdir}'")
for file_name in matching_files:
print(f"{file_name} - Latest file available")
else:
print(f"{file_name} - Latest file not available")
if subdir.__contains__(now+"\Test_Results_2"):
if len(matching_files) > 0:
print(f"\nFiles are present in '{subdir}'")
for file_name in matching_files:
print(f"{file_name} - Latest file available")
else:
print(f"{file_name} - Latest file not available")