如何从Python中的路径获取没有扩展名的文件名?

2024-03-28 11:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
0条回答
网友
1楼 · 发布于 2024-03-28 11:00:53
>>> print(os.path.splitext(os.path.basename("hemanth.txt"))[0])
hemanth
网友
2楼 · 发布于 2024-03-28 11:00:53

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

import os
print(os.path.splitext("/path/to/some/file.txt")[0])

印刷品:

/path/to/some/file

重要提示:如果文件名有多个点,则只删除最后一个点之后的扩展名。例如:

import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])

印刷品:

/path/to/some/file.txt.zip

如果你需要处理这个案子,请看下面的其他答案。

网友
3楼 · 发布于 2024-03-28 11:00:53

你可以自己做:

>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'

重要提示:如果文件名中有多个.,则只删除最后一个。例如:

/root/dir/sub/file.ext.zip -> file.ext

/root/dir/sub/file.ext.tar.gz -> file.ext.tar

请参阅下面的其他答案。

相关问题 更多 >