How to get the filename without the extension from

2019-01-01 09:22发布

How to get the filename without the extension from a path in Python?

19条回答
忆尘夕之涩
2楼-- · 2019-01-01 09:59

Just roll it:

>>> 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'
查看更多
大哥的爱人
3楼-- · 2019-01-01 09:59

os.path.splitext() won't work if there are multiple dots in the extension.

For example, images.tar.gz

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar

You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images
查看更多
步步皆殇っ
4楼-- · 2019-01-01 10:01
>>> print(os.path.splitext(os.path.basename("hemanth.txt"))[0])
hemanth
查看更多
不流泪的眼
5楼-- · 2019-01-01 10:01

import os

filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv

This returns the filename without the extension(C:\Users\Public\Videos\Sample Videos\wildlife)

temp = os.path.splitext(filename)[0]  

Now you can get just the filename from the temp with

os.path.basename(temp)   #this returns just the filename (wildlife)
查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 10:03
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]
查看更多
大哥的爱人
7楼-- · 2019-01-01 10:04

https://docs.python.org/3/library/os.path.html

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c
查看更多
登录 后发表回答