是否有从文件名中提取扩展名的功能?


当前回答

使用os.path.splitext:

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

与大多数手动字符串拆分尝试不同,os.path.splitext将正确地将/a/b.c/d视为没有扩展名而不是扩展名.c/d,并将.bashrc视为没有延伸名而不是具有扩展名.bashrc:

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')

其他回答

3.4版新增。

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'
print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz']

我很惊讶还没有人提到pathlib,pathlib太棒了!

此方法需要字典、列表或集合。您可以使用内置字符串方法使用“.endswitch”。这将在文件末尾的列表中搜索名称,只需使用str.endswith(fileName[index])即可完成。这更多用于获取和比较扩展名。

https://docs.python.org/3/library/stdtypes.html#string-方法

示例1:

dictonary = {0:".tar.gz", 1:".txt", 2:".exe", 3:".js", 4:".java", 5:".python", 6:".ruby",7:".c", 8:".bash", 9:".ps1", 10:".html", 11:".html5", 12:".css", 13:".json", 14:".abc"} 
for x in dictonary.values():
    str = "file" + x
    str.endswith(x, str.index("."), len(str))

示例2:

set1 = {".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"}
for x in set1:
   str = "file" + x
   str.endswith(x, str.index("."), len(str))

示例3:

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
for x in range(0, len(fileName)):
    str = "file" + fileName[x]
    str.endswith(fileName[x], str.index("."), len(str))

示例4

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
str = "file.txt"
str.endswith(fileName[1], str.index("."), len(str))

具有输出的示例5、6、7

示例8

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
exts = []
str = "file.txt"
for x in range(0, len(x)):
    if str.endswith(fileName[1]) == 1:
         exts += [x]
     

使用splitext时,具有双扩展名的文件存在问题(例如file.tar.gz、file.tar.bz2等)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

但应该是:.tar.gz

可能的解决方案如下

import os.path
extension = os.path.splitext(filename)[1]

您可以在pathlib模块(python3.x中提供)中找到一些很棒的东西。

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

# Output 
'.txt'