2 回答
TA贡献1898条经验 获得超8个赞
如果可能的话,我总是更喜欢使用 os 内置的路径并捕获不受支持的类型
import os
video_types = ('.mp4', '.avi', '.jpeg')
image_types = ('.png', '.jpg')
filenames = ["/test/1.jpg","/test/2.avi","/test/unknown.xml","/test/noextention"]
for filename in filenames:
print(filename)
if os.path.splitext(filename)[1] in video_types:
print("Its a Video")
elif os.path.splitext(filename)[1] in image_types:
print("Its an Image")
else:
print("No Idea")
/test/1.jpg
Its an Image
/test/2.avi
Its a Video
/test/unknown.xml
No Idea
/test/noextention
No Idea
TA贡献1829条经验 获得超7个赞
from urlparse import urlparse
from os.path import splitext
url = "sample/test/image.png"
image_formats = [".png", ".jpeg"]
video_formats = [".mp4", ".mp3", ".avi"]
def get_ext(url):
"""Return the filename extension from url, or ''."""
parsed = urlparse(url)
root, ext = splitext(parsed.path)
return ext
if get_ext(url) in image_formats:
print("it's an image")
elif get_ext(url) in video_formats:
print("it's a video")
else:
print("some differnet format")
它适用于任何类型的网址
www.example.com/image.jpg
https://www.example.com/page.html?foo=1&bar=2#fragment
https://www.example.com/resource
添加回答
举报