简体   繁体   中英

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?

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, eg file.name , file.stat() , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM