如何在python中找到文件名

我有个问题。我对此有点困惑。我有来自其中的图像和视频的 URL。我想从该链接中获取名称并检查它是图像还是视频并对其执行操作。喜欢


if filename.endwith(.jpg or .png):

   print("it's an image")

else filename.endwith(.mp4, .avi):

   print("it's a video) 

文件名是一个列表。所有数据都存储在其中:


        ls = ["C:/Users/OB/Desktop/DevoMech Project/6.JPG" , "C:/Users/OB/Desktop/DevoMech Project/7.JPG"]


    if ls.endwith(.JPG or .JPEG):


        item1 = QtWidgets.QListWidgetItem(QIcon(ls), "item1")

        self.dlistWidget.addItem(item1)

        #item2 = QtWidgets.QListWidgetItem(QIcon("C:/Users/OB/Desktop/DevoMech Project/7.JPEG"), "item2")

        self.dlistWidget.addItem(item2)

而不是第一项,而是显示实际名称。


蝴蝶刀刀
浏览 88回答 2
2回答

汪汪一只猫

如果可能的话,我总是更喜欢使用 os 内置的路径并捕获不受支持的类型import osvideo_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.jpgIts an Image/test/2.aviIts a Video/test/unknown.xmlNo Idea/test/noextentionNo Idea

千巷猫影

from urlparse import urlparsefrom os.path import splitexturl = "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.jpghttps://www.example.com/page.html?foo=1&bar=2#fragmenthttps://www.example.com/resource
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python