假设:>>> files = {"a_movie.mkv", "an_image.png", "a_movie_without_extension", "an_image_without_extension"}
它们是脚本文件夹中合适的电影和图像文件。
您可以使用内置的mimetypes模块,但如果没有扩展,它将无法工作。>>> import mimetypes
>>> {file: mimetypes.guess_type(file) for file in files}
{'a_movie_without_extension': (None, None), 'an_image.png': ('image/png', None), 'an_image_without_extension': (None, None), 'a_movie.mkv': (None, None)}
或者调用unix命令file。这在没有扩展名的情况下工作,但在Windows中不行:>>> import subprocess
>>> def find_mime_with_file(path):
... command = "/usr/bin/file -i {0}".format(path)
... return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0].split()[1]
...
>>> {file: find_mime_with_file(file) for file in files}
{'a_movie_without_extension': 'application/octet-stream;', 'an_image.png': 'image/png;', 'an_image_without_extension': 'image/png;', 'a_movie.mkv': 'application/octet-stream;'}
或者尝试使用PIL打开它,并检查是否有错误,但需要安装PIL:>>> from PIL import Image
>>> def check_image_with_pil(path):
... try:
... Image.open(path)
... except IOError:
... return False
... return True
...
>>> {file: check_image_with_pil(file) for file in files}
{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': True, 'a_movie.mkv': False}
或者,为了简单起见,正如你所说,只需检查扩展,这是我认为最好的方法。>>> extensions = {".jpg", ".png", ".gif"} #etc
>>> {file: any(file.endswith(ext) for ext in extensions) for file in files}
{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': False, 'a_movie.mkv': False}