Python glob but against a list of strings rather than the filesystem

后端 未结 9 1781
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 21:24

I want to be able to match a pattern in glob format to a list of strings, rather than to actual files in the filesystem. Is there any way to do this, or convert a glob

9条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 21:43

    An extension to @Veedrac PurePath.match answer that can be applied to a lists of strings:

    # Python 3.4+
    from pathlib import Path
    
    path_list = ["foo/bar.txt", "spam/bar.txt", "foo/eggs.txt"]
    # convert string to pathlib.PosixPath / .WindowsPath, then apply PurePath.match to list
    print([p for p in path_list if Path(p).match("ba*")])  # "*ba*" also works
    # output: ['foo/bar.txt', 'spam/bar.txt']
    
    print([p for p in path_list if Path(p).match("*o/ba*")])
    # output: ['foo/bar.txt']
    

    It is preferable to use pathlib.Path() over pathlib.PurePath(), because then you don't have to worry about the underlying filesystem.

提交回复
热议问题