是否有从文件名中提取扩展名的功能?
当前回答
这是一种直接的字符串表示技术:我看到提到了很多解决方案,但我认为大多数都在考虑拆分。然而,每次出现“.”时,Split都会执行此操作。您更希望查找的是分区。
string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
其他回答
这是一种直接的字符串表示技术:我看到提到了很多解决方案,但我认为大多数都在考虑拆分。然而,每次出现“.”时,Split都会执行此操作。您更希望查找的是分区。
string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
使用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', '')
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
import os.path
extension = os.path.splitext(filename)[1]
您可以对文件名使用拆分:
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
这不需要额外的库