Extracting extension from filename in Python

后端 未结 24 2138
感情败类
感情败类 2020-11-22 13:23

Is there a function to extract the extension from a filename?

相关标签:
24条回答
  • 2020-11-22 14:19

    Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:

    to get extension of a given file absolute path, you can simply type:

    filepath.rpartition('.')[-1]
    

    example:

    path = '/home/jersey/remote/data/test.csv'
    print path.rpartition('.')[-1]
    

    will give you: 'csv'

    0 讨论(0)
  • 2020-11-22 14:19

    A true one-liner, if you like regex. And it doesn't matter even if you have additional "." in the middle

    import re
    
    file_ext = re.search(r"\.([^.]+)$", filename).group(1)
    

    See here for the result: Click Here

    0 讨论(0)
  • 2020-11-22 14:20
    import os.path
    extension = os.path.splitext(filename)[1][1:]
    

    To get only the text of the extension, without the dot.

    0 讨论(0)
  • 2020-11-22 14:20

    You can find some great stuff in pathlib module (available in python 3.x).

    import pathlib
    x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
    print(x)
    
    # Output 
    '.txt'
    
    0 讨论(0)
  • 2020-11-22 14:20

    You can use a split on a filename:

    f_extns = filename.split(".")
    print ("The extension of the file is : " + repr(f_extns[-1]))
    

    This does not require additional library

    0 讨论(0)
  • 2020-11-22 14:21

    New in version 3.4.

    import pathlib
    
    print(pathlib.Path('yourPath.example').suffix) # '.example'
    

    I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

    If you need all the suffixes (eg if you have a .tar.gz), .suffixes will return a list of them!

    0 讨论(0)
提交回复
热议问题