Python获取文件扩展名的5种简单方法 | 完整教程
我们可以使用Python的os模块的splitext()函数来获取文件的扩展名。这个函数将文件路径拆分为一个包含两个值的元组 – 根路径和扩展名。
在Python中获取文件扩展名
这是一个在Python中获取文件扩展名的简单程序。
import os
# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/scdev/abc.txt")
print(file_name)
print(file_extension)
print(os.path.splitext("/Users/scdev/.bashrc"))
print(os.path.splitext("/Users/scdev/a.b/image.png"))
输出:

- In the first example, we are directly unpacking the tuple values to the two variables.
- Note that the .bashrc file has no extension. The dot is added to the file name to make it a hidden file.
- In the third example, there is a dot in the directory name.
使用Pathlib模块获取文件扩展名
我们也可以使用pathlib模块来获取文件扩展名。该模块在Python 3.4发布中引入。
>>> import pathlib
>>> pathlib.Path("/Users/scdev/abc.txt").suffix
'.txt'
>>> pathlib.Path("/Users/scdev/.bashrc").suffix
''
>>> pathlib.Path("/Users/scdev/.bashrc")
PosixPath('/Users/scdev/.bashrc')
>>> pathlib.Path("/Users/scdev/a.b/abc.jpg").suffix
'.jpg'
>>>
结论
最好使用标准的方法来获取文件扩展名。如果您已经在使用 os 模块,那么请使用 splitext() 方法。对于面向对象的方法,请使用 pathlib 模块。