Skip to content

Instantly share code, notes, and snippets.

@AlmightyOatmeal
Last active May 8, 2018 23:04
Show Gist options
  • Save AlmightyOatmeal/be49c93779905cb57d411384de3d8e86 to your computer and use it in GitHub Desktop.
Save AlmightyOatmeal/be49c93779905cb57d411384de3d8e86 to your computer and use it in GitHub Desktop.
Fun with Python and mimetypes! Works in Python 2.7.x.
import mimetypes
import os
def find_files(root, accepted_types=None):
"""Walk a path and find files that are a specific type, regardless of extension.
:param root: Path to start walking for files.
:type root: str
:param accepted_types: (optional) List of acceptable mimetypes to match.
(default: None)
:type accepted_types: list
:return: List of full file paths that match the mimetypes.
:rtype: list
"""
if accepted_types is None:
accepted_types = [
'video/mp4',
'video/x-msvideo'
]
results = []
for root, root_subdirs, root_files in os.walk(root):
# Skip empty directories.
if not root_files:
continue
for root_file in root_files:
file_path = os.path.join(root, root_file)
if os.path.isdir(file_path):
continue
mime_results = mimetypes.guess_type(file_path)
if mime_results[0] not in accepted_types:
continue
results.append(file_path)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment