Search code examples
pythonfor-loopnestedassertos.walk

In a for loop, how can I assign the variable to a specific file-type?


I'm using the os.walk command in python to go through all of a directory's contents. I'm running a secondary for loop on the files inside all of the folders and sub-folders in the directory. An error pops up saying it doesn't know how to deal with the .txt files present (my code is specific to .png files). I want the secondary for loop to run on ONLY .png filetypes and ignore the .txt or other files in the folder with the .png images. I tried the assert command, but couldn't get it to work. How can I make it restrictive to .png files?

for root, dirs, files in os.walk(r"/mnt/c/Users/james/Documents/ListingTest/", topdown=True):
    for image in files:
        assert image is filetype: .png
        print(os.path.join(root, image))
        

I couldn't get the assert function syntax right and don't even know if it is the command I need to use.


Solution

  • Try:

    for image in files:
        if image.lower().endswith(".png"):
            print(os.path.join(root, image))
    

    This would print all the paths of files ending with .png. As mentioned in the comments, this does not actually guarantee that the file is an image. Any file with the mentioned extension will be printed.