Getting file extension using pattern matching in python

后端 未结 6 1317
逝去的感伤
逝去的感伤 2020-12-11 19:58

I am trying to find the extension of a file, given its name as a string. I know I can use the function os.path.splitext but it does not work as expected in case

6条回答
  •  旧巷少年郎
    2020-12-11 20:07

    Starting from phihags answer:

    DOUBLE_EXTENSIONS = ['tar.gz','tar.bz2'] # Add extra extensions where desired.
    
    def guess_extension(filename):
        """
        Guess the extension of given filename.
        """
        root,ext = os.path.splitext(filename)
        if any([filename.endswith(x) for x in DOUBLE_EXTENSIONS]):
            root, first_ext = os.path.splitext(root)
            ext = first_ext + ext
        return root, ext
    

提交回复
热议问题