Extracting extension from filename in Python

2019-01-01 02:53发布

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

20条回答
人间绝色
2楼-- · 2019-01-01 03:19
name_only=file_name[:filename.index(".")

That will give you the file name up to the first ".", which would be the most common.

查看更多
时光乱了年华
3楼-- · 2019-01-01 03:20
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
查看更多
骚的不知所云
4楼-- · 2019-01-01 03:22

You can find some great stuff in pathlib module.

import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)

# Output 
'.txt'
查看更多
萌妹纸的霸气范
5楼-- · 2019-01-01 03:24

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'

查看更多
初与友歌
6楼-- · 2019-01-01 03:24

Just join all pathlib suffixes.

>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'
查看更多
刘海飞了
7楼-- · 2019-01-01 03:25

One option may be splitting from dot:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

No error when file doesn't have an extension:

>>> "filename".split(".")[-1]
'filename'

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension
查看更多
登录 后发表回答