python获取文件后缀名_如何在Python中获取文件扩展名

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 Python

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获取文件后缀名

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值