回答
你应该为此使用一个库。请注意,扩展名!=文件类型,因为您可以将扩展名更改为.jpg文件,使用油漆打开它,油漆会将其解释为像jpeg(例如)。你应该检查How to find the mime type of a file in python?。
这已被提及 - 这应该是一个评论,而不是回答 –
假设:
>>> 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}
+1注意到其他人使用'文件'或选项二最适合我的使用情况下,我爬行检索无返回的图像扩展名,并需要将它们保存为.jpg/.png – matchew
还有一个简单的方法来解决这个问题....“request.files中的if file':”如果有文件,试试这个,那么它将返回true。 。 –
- 1. 检测上传的文件是否是PHP中的图像
- 2. 如何检测文件是否是perl中的图像
- 3. 如何检测href是否是图像?
- 4. 检测文件是否是Python中的视频?
- 5. 检测ColdFusion中图像是否模糊
- 6. 图像中检测是否在Javascript
- 7. 检测图像中是否存在球
- 8. 如何检测文件是否是PHP中的图标?
- 9. 是否有可能检测到重复的图像文件?
- 10. 检查文件是否为图像
- 11. 检查文件是否为图像
- 12. 如何检查文件是否是C++中的图像类型?
- 13. 检测图像控件是否已完成更新其图像
- 14. 检测图像是否有水印?
- 15. 检查文件是否是任何图像(一般检查) - PHP
- 16. 检测文件是否在python中的网络驱动器上
- 17. 检测给定的文件是否为图像,并且是java中特定类型的有效图像
- 18. python检测文档中的图像
- 19. 检查文件是否是有效的图像
- 20. 检查文件是否是aws上的图像或xml S3
- 21. 检测文本中的链接,并确定它是否是图像
- 22. 如何检测文件路径是否用Python封装在“..”中?
- 23. 如何检测图像是否是方形的?
- 24. 检查图像是否是单色的
- 25. Python:检查“两个”.doc文件是否是相同的文件?
- 26. 检测文件是否是Java 8中的符号链接
- 27. 检查图像是否包含文字?
- 28. 检查图像是否
- 29. 检测是否从一个图像中的对象与OpenCV的
- 30. 检测文件是否打开
根据标准的python文件类型http://docs.python.org/c-api/concrete.html图像文件不是标准的,所以我猜想会需要一些外部模块。 – timonti
使用'imghdr'模块。请参阅[如何检查文件是否是有效的图像文件?](http://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file) –