Search code examples
pythonpython-3.xos.walk

Specific file extension in os.walk()


I have the following code:

path = "/path/to/directory/"
for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        file = os.path.join(dirpath, filename)
        folder = os.path.basename(dirpath)
        filesize = os.path.getsize(file)

The only problem is that I would like to filter and get the information only for the mp4 files, excluding the others from the search.

I tried to add *.mp4 at the end of path without success, how I can do that?


Solution

  • os.walk() requires a single directory argument, so you can't use wildcards. You could filter the contents of filenames but it's probably easier to just do this:

    path = "/path/to/directory/"
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if not filename.endswith(".mp4"):
                continue
            file = os.path.join(dirpath, filename)
            folder = os.path.basename(dirpath)
            filesize = os.path.getsize(file)
    

    Alternatively, you could use the more modern and preferred pathlib; this will find all .mp4 files recursively:

    from pathlib import Path
    
    path = "/path/to/directory/"
    for file in Path(path).rglob("*.mp4"):
        [....]
    

    Each file object will have attributes and methods you can use to obtain information about the file, e.g. file.name, file.stat(), etc.