Good day! Tell me how can I list the files in the folder with a specific extension?

Found on the Internet a piece of code:

import os directory = './' files = os.listdir(directory) fzip = filter(lambda x: x.endswith('.zip'), files) 

The script is executed print(fzip) but I get instead of (f1.zip, f2.zip ...) <filter object at 0x0318C990>

What could be the problem? Thanks in advance for your help.

  • one
    from glob import glob; glob.glob('/path/to/*.zip') from glob import glob; glob.glob('/path/to/*.zip') ? - MaxU
  • If you are wondering what other options besides listdir + endswith may be (for example, pathlib.Path(directory).glob('*.zip') ), then you can also ask your original question "Search for files by extension in Python" ask (if the search does not find such a question). - jfs

1 answer 1

filter() in Python 3 returns a lazy collection — an iterator. To get the items, you need to bypass the result. For example, to print items separated by a space:

 print(*fzip) 

See What does it mean * (asterisk) and ** double star in Python?

If you want to bypass fzip , save the result to the list during the first traversal:

 zip_paths = list(fzip) print(*zip_paths) for path in zip_paths: # use path here...