1

I seem to be stuck on some logic within my code and would appreciate any insight. My objective is to find an excel file in two different sub folders. The user inputs the ID number in the terminal (which is the name of the root folder) and create a file path with the ID. Now im not sure why my if statement isn't detecting the file in either folder.

If anyone can look at my code, it would be greatly appreciated.

#ask user to input the ID
ID = input("Please enter folder ID: ")

#path of excel directory and use glob
path = "/Users/one/Downloads/" + str(ID) + "/"

for (dir,subdirs,files) in os.walk(path):
    if "Filey1_*.xlsx" in files:
        print("File Found:", os.path.join(dir, "Filey1_*.xlsx"))
2
  • Maybe a bit off-topic but I would highly suggest you not to use dir as a variable because it is a built-in function.
    – Hammad
    Commented Aug 20, 2021 at 1:01
  • @HammadAli, any suggestions? I've done: f or f in os.walk(path): however it did not work Commented Aug 20, 2021 at 1:04

3 Answers 3

2

So the issue is with your if statement as it searches for exact "Filey1_*.xlsx" match in the file names.

You can try using something like this:

for (root, subdirs, files) in os.walk(path):
  for f in files:
    if "Filey1_" in f and ".xlsx" in f:
      print("File Found:", os.path.join(root, f))
2

To answer your question directly: the reason your if statement is not working is because the use of the keyword "in" is not like using glob or a regex and the asterisk you're including (*) is not doing what you think it is doing. In fact it's not really doing anything. The result is that you're searching specifically for a file called exactly "Filey1_*.xlsx" rather than a file that matches the glob regex (* being a wild card), which is presumably what you want.

What you could do is add this import at the top:

from pathlib import Path

and then replace your if statement with:

temp = Path(path).rglob("Filey1_*.xlsx")
temp = list(temp)
if len(temp) > 0:
    print("File Found:", os.path.join(dir, str(temp[0])))

the first line does a recursive glob search through all subfolders of path and if it finds a file, then the list length is larger than 0.

0

I found a really simple solution to my own problem lol I'll share it with everyone!

files = glob.glob(path + "/**/Filey1_*.xlsx", recursive = True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.