varsayarsak.
Yerleşik mimetek modülünü kullanabilirsiniz, ancak uzantı olmadan çalışmayacaktır.
>>> 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)}
Veya unix komutunu file
diyoruz. senin gibi, basitlik için,
>>> 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}
Veya: Bu uzantılar olmadan çalışır, ancak 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;'}
Yoksa PIL ile açın ve hataları denetlemek için çalışıyorum, ama yüklü PIL ihtiyacı Sadece uzantıları kontrol et, düşündüğüm en iyi yol.
>>> 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}
Standart python dosya türlerine göre http://docs.python.org/c-api/concrete.html görüntü dosyası standart değildir, bu nedenle bazı dış modüllerin gerekeceğini varsayalım. – timonti
'imghdr modülünü kullanın. Bkz. [Bir dosyanın geçerli bir resim dosyası olup olmadığı nasıl kontrol edilir?] (Http://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file) –