Extracting extension from filename in Python

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

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

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

    Even this question is already answered I'd add the solution in Regex.

    >>> import re
    >>> file_suffix = ".*(\..*)"
    >>> result = re.search(file_suffix, "somefile.ext")
    >>> result.group(1)
    '.ext'
    
    0 讨论(0)
  • 2020-11-22 14:15
    def NewFileName(fichier):
        cpt = 0
        fic , *ext =  fichier.split('.')
        ext = '.'.join(ext)
        while os.path.isfile(fichier):
            cpt += 1
            fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
        return fichier
    
    0 讨论(0)
  • 2020-11-22 14:16

    Another solution with right split:

    # to get extension only
    
    s = 'test.ext'
    
    if '.' in s: ext = s.rsplit('.', 1)[1]
    
    # or, to get file name and extension
    
    def split_filepath(s):
        """
        get filename and extension from filepath 
        filepath -> (filename, extension)
        """
        if not '.' in s: return (s, '')
        r = s.rsplit('.', 1)
        return (r[0], r[1])
    
    0 讨论(0)
  • 2020-11-22 14:16

    try this:

    files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
    pen_ext = ['foo', 'tar', 'bar', 'etc']
    
    for file in files: #1
        if (file.split(".")[-2] in pen_ext): #2
            ext =  file.split(".")[-2]+"."+file.split(".")[-1]#3
        else:
            ext = file.split(".")[-1] #4
        print (ext) #5
    
    1. get all file name inside the list
    2. splitting file name and check the penultimate extension, is it in the pen_ext list or not?
    3. if yes then join it with the last extension and set it as the file's extension
    4. if not then just put the last extension as the file's extension
    5. and then check it out
    0 讨论(0)
  • 2020-11-22 14:18

    Yes. Use os.path.splitext(see Python 2.X documentation or Python 3.X documentation):

    >>> import os
    >>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
    >>> filename
    '/path/to/somefile'
    >>> file_extension
    '.ext'
    

    Unlike most manual string-splitting attempts, os.path.splitext will correctly treat /a/b.c/d as having no extension instead of having extension .c/d, and it will treat .bashrc as having no extension instead of having extension .bashrc:

    >>> os.path.splitext('/a/b.c/d')
    ('/a/b.c/d', '')
    >>> os.path.splitext('.bashrc')
    ('.bashrc', '')
    
    0 讨论(0)
  • 2020-11-22 14:18

    This is The Simplest Method to get both Filename & Extension in just a single line.

    fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')
    
    >>> print(fName)
    Flower
    >>> print(ext)
    jpeg
    

    Unlike other solutions, you don't need to import any package for this.

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