pythonos.walk

How can I limit os.walk results for a single file?


I am trying to search a given directory for a specific file, and if that file does not exist I would want the code to say "File does not exist". Currently with os.walk I can get this to work, however this will hit on every single file that isn't the specified file and print "File dos not exist". I know that this is how os.walk functions, but I was not sure if there is a way to make it only print out once if it is found or not found.

Folder structure:

root folder| |Project Folder |file.xml |other files/subfolders

How I would want the code to work is to go inside of "Project Folder", do a recursive search for "file.xml", and once it is found print out once "Found", otherwise prints out once "Not found".

The code is:

def check_file(x): #x = root folder dir
   for d in next(os.walk(x))[1]: #if I understand correctly, [1] will be Project Folder
        for root, directories, files in os.walk(x):
            for name in files:
                if "file.xml" not in name:
                    print("found")
                else:
                    print("File Missing")

If I change the code to

            for name in files:
                if "file.xml" in name:
                    print("found")
                else:
                    pass

The code technically works as intended, but it doesn't really do much to help point out if it isn't there, so this isn't a good solution. It would be easier if I was able to give the code a specific path to look in, however as the user is able to place the 'root folder' anywhere on their machine as well as the 'project folder' would have different names depending on the project, I don't think I would be able to give the code a specific location.

Is there a way to get this to work with os.walk, or would another method work best?


Solution

  • The glob module is very convenient for this kind of wildcard-based recursive search. Particularly, the ** wildcard matches a directory tree of arbitrary depth, so you can find a file anywhere in the descendants of your root directory.

    For example:

    import glob
    
    def check_file(x):  # where x is the root directory for the search
        files = glob.glob('**/file.xml', root_dir=x, recursive=True)
        if files:
            print(f"Found {len(files)} matching files")
        else:
            print("Did not find a matching file")