python获取文件后缀名
We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values – root and extension.
我们可以使用Python os模块 splitext()函数来获取文件扩展名。 此函数将文件路径拆分为具有两个值的元组-root和extension。
在Python中获取文件扩展名 (Getting File Extension in Python)
Here is a simple program to get the file extension in Python.
这是一个使用Python获取文件扩展名的简单程序。
- import os
-
- # unpacking the tuple
- file_name, file_extension = os.path.splitext("/Users/pankaj/abc.txt")
-
- print(file_name)
- print(file_extension)
-
- print(os.path.splitext("/Users/pankaj/.bashrc"))
- print(os.path.splitext("/Users/pankaj/a.b/image.png"))
Output:
输出 :

File Extension in Python
Python中的文件扩展名
- 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.
请注意,.bashrc文件没有扩展名。 点被添加到文件名以使其成为隐藏文件。
- In the third example, there is a dot in the directory name.
在第三个示例中,目录名称中有一个点。
使用Pathlib模块获取文件扩展名 (Get File Extension using Pathlib Module)
We can also use pathlib module to get the file extension. This module was introduced in Python 3.4 release.
我们还可以使用pathlib模块获取文件扩展名。 该模块在Python 3.4版本中引入。
- >>> import pathlib
- >>> pathlib.Path("/Users/pankaj/abc.txt").suffix
- '.txt'
- >>> pathlib.Path("/Users/pankaj/.bashrc").suffix
- ''
- >>> pathlib.Path("/Users/pankaj/.bashrc")
- PosixPath('/Users/pankaj/.bashrc')
- >>> pathlib.Path("/Users/pankaj/a.b/abc.jpg").suffix
- '.jpg'
- >>>
结论 (Conclusion)
It’s always better to use the standard methods to get the file extension. If you are already using the os module, then use the splitext() method. For the object-oriented approach, use the pathlib module.
最好使用标准方法来获取文件扩展名。 如果您已经在使用os模块,请使用splitext()方法。 对于面向对象的方法,请使用pathlib模块。
翻译自: https://www.journaldev.com/32081/get-file-extension-in-python
python获取文件后缀名