I'm trying to loop through a folder and all subfolders to find all files of certain file types - for example, only .mp4, .avi, .wmv.
Here is what I have now, it loops through all file types:
import os
rootdir = 'input'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print (os.path.join(subdir, file))
We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.
To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.
Use a for-loop to iterate through the lines of a file In a with-statement, use open(file, mode) with mode as "r" to open file for reading. Inside the with-statement, use a for-loop to iterate through the lines. Then, call str. strip() to strip the end-line break from each line.
For multiple extensions, the simplest is just to use str.endswith
passing a tuple of substrings to check:
for file in files:
if file.endswith((".avi",".mp4","wmv")):
print (os.path.join(subdir, file))
You could use iglob
like below and chain the searches returned or use re.search but using endswith
is probably the best approach.
from itertools import chain
from glob import iglob
for subdir, dirs, files in os.walk(rootdir):
for file in chain.from_iterable(iglob(os.path.join(rootdir,p)) for p in ("*.avi", "*.mp4", "*wmv")) :
print(os.path.join(subdir, file))
Using python3.5
glob now supports recursive searches with the ** syntax:
from itertools import chain
from glob import iglob
from glob import iglob
for file in chain.from_iterable(iglob(os.path.join(rootdir,p))
for p in (rootdir+"**/*.avi", "**/*.mp4", "**/*wmv")):
print(file)
You can use os.path.splitext
which takes a path and splits the file extension from the end of it:
import os
rootdir = 'input'
extensions = ('.mp4', '.avi', '.wmv')
for subdir, dirs, files in os.walk(rootdir):
for file in files:
ext = os.path.splitext(file)[-1].lower()
if ext in extensions:
print (os.path.join(subdir, file))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With