python去除扩展名


本文摘自php中文网,作者不言,侵删。

下面为大家分享一篇python去除扩展名的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

获取不带扩展名的文件的名称:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

import os

printos.path.splitext("path_to_file")[0]

  

from os.path import basename

# now you can call it directly with basename

print basename("/a/b/c.txt")

  

>>>base=os.path.basename('/root/dir/sub/file.ext')

>>> base

'file.ext'

>>> os.path.splitext(base)

('file', '.ext')

>>> os.path.splitext(base)[0]

'file'

>>>

>>> printos.path.splitext(os.path.basename("hemanth.txt"))[0]

hemanth

>>> file ='/root/dir/sub.exten/file.data.1.2.dat'

>>> print('.').join(file.split('.')[:-1])

/root/dir/sub.exten/file.data.1.2

  

>>> s = 'c:\\temp\\akarmi.txt'

>>> print(os.path.splitext(s)[0])

c:\temp\akarmi

因此,我不需要驱动器号或者目录名,我使用:

  

>>>print(os.path.splitext(os.path.basename(s))[0])

akarmi

def getFileNameWithoutExtension(path):

 returnpath.split('\\').pop().split('/').pop().rsplit('.', 1)[0]

  

getFileNameWithoutExtension('/path/to/file-0.0.1.ext')

# => file-0.0.1

  

getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')

# => file-0.0.1

相关推荐:

python去除空格和换行符的实例代码

python3 遍历删除特定后缀名文件的方法

以上就是python去除扩展名的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中elif可以单独使用吗

利用Python反向输出一个字符串

Python32位和64位有什么区别

Python中的value是什么

Python如何将数字转化为字符串

Python pop函数的定义及使用方式(实例展示)

Python的错误与异常处理

Python中“//”表示什么意思

Python中join是什么意思

Python爬虫是什么?为什么把Python叫做爬虫?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...