Home > Backend Development > Python Tutorial > python remove extension

python remove extension

不言
Release: 2018-04-23 17:05:59
Original
4592 people have browsed it

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

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

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
Copy after login

相关推荐:

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

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

The above is the detailed content of python remove extension. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template