代码之家  ›  专栏  ›  技术社区  ›  Mave

使用带字符串的大小写匹配。endswith()处理不同的可能字符串结尾

  •  0
  • Mave  · 技术社区  · 2 年前

    我想遍历一个目录,并根据扩展名将文件排序到单独的列表中。我想使用match case来实现这一点,而不是使用许多单独的If。 大致如下:

    for file in os.listdir(dirpath):
        filename = os.fsdecode(file)
        match filename.endswith():
            case endswith('.jpg')|endswith('.jpeg'): #How can I check if the 'filename' string ends with these two?
                doSomething(filename)
            case endswith('.mp4'): #Or this?
                somethingElse(filename)
            case _: #Or if it is anything else?
                doDefault(filename)
    

    1 回复  |  直到 2 年前
        1
  •  4
  •   M.O.    2 年前

    os.path.splitext 分离文件扩展名,然后运行匹配。类似于

    for file in os.listdir(dirpath):
        filename = os.fsdecode(file)
        _, extension = os.path.splitext(filename)
        match extension:
            case '.jpg' | 'jpeg':
                doSomething(filename)
            case '.mp4':
                somethingElse(filename)
            case _:
                doDefault(filename)