如何在Python中从路径中获取没有扩展名的文件名?
"/path/to/some/file.txt" → "file"
>>> from pathlib import Path
>>> Path("/path/to/file.txt").stem
'file'
>>> Path("/path/to/file.tar.gz").stem
'file.tar'
使用os.path.splitext
与os.path.basename
组合使用:
>>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
'file'
>>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]
'file.tar'
splitext(basename('/some/path/to/file.txt'))[0]
(我似乎总是这样做)。 - CpILLos.path
解决方案一样,这只会删除一个扩展名(或者pathlib
称为suffix
的内容)。例如,Path('a.b.c').stem == 'a.b'
。 - BallpointBen.with_suffix('')
是可行的方法。你可能需要循环,直到 p.suffix == ''
。 - BallpointBenpathlib.Path('backup.tar.gz').stem
-> 'backup.tar
但期望结果为 backup
。 - pymenFantastic Mr.Fox.mp4
呢? - spectras>>> 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
请参阅下面其他回答的内容。
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
\
来显示代码,例如路径实例为"/somepath/hermanth.txt"。 - cregox在Python 3.4+中,您可以使用pathlib
解决方案
from pathlib import Path
print(Path(your_path).resolve().stem)
resolve()
解析路径?如果不使用它,是否可能得到不包含文件名的路径?这意味着如果给定一个符号链接的路径,您将返回符号链接指向的文件的文件名(不带扩展名)。 - user3064538resolve()
的一个可能原因是帮助解决多个点的问题。如果路径为 "./foo.tar.gz",则下面关于使用索引的答案将不起作用。 - William Allcockhttps://docs.python.org/zh-cn/3/library/os.path.html
在Python 3中,pathlib模块提供了高级路径对象。
所以,>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> p.with_suffix('')
WindowsPath('/a/b/c')
>>> p.stem
'c'
正如@IceAdor在评论中提到@user2902201的解决方案,rsplit
是最简单的解决方案之一,适用于多个句点(通过将分割数限制为从字符串结尾开始的maxsplit
仅为1)。
这里是详细说明:
file = 'my.report.txt'
print file.rsplit('.', maxsplit=1)[0]
my.report
./readme
,则此方法将失败。 - Wolf如果扩展名中有多个点,os.path.splitext()将无法正常工作。
例如,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
你可以找到基本名称中第一个句点的索引,然后切片基本名称以获取没有扩展名的文件名。>>> 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
.
),则'haystack'.index('needle')
会引发ValueError异常。也存在没有任何扩展名的文件。 - Czechnologystr.find()
并检查是否为-1。如果没有点,则只需返回file_name
。 - Starwarswii>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2
'/root/dir/sub.exten/file.data.1.2.dat'.rsplit('.', 1)
。 - IceArdor使用Pathlib,当只有一个扩展名(或没有)时获取文件名非常简单,但处理多个扩展名的一般情况可能会很棘手。
from pathlib import Path
pth = Path('./thefile.tar')
fn = pth.stem
print(fn) # thefile
# Explanation:
# the `stem` attribute returns only the base filename, stripping
# any leading path if present, and strips the extension after
# the last `.`, if present.
# Further tests
eg_paths = ['thefile',
'thefile.tar',
'./thefile',
'./thefile.tar',
'../../thefile.tar',
'.././thefile.tar',
'rel/pa.th/to/thefile',
'/abs/path/to/thefile.tar']
for p in eg_paths:
print(Path(p).stem) # prints thefile every time
from pathlib import Path
pth = Path('./thefile.tar.gz')
fn = pth.with_suffix('').stem
print(fn) # thefile
# Explanation:
# Using the `.with_suffix('')` trick returns a Path object after
# stripping one extension, and then we can simply use `.stem`.
# Further tests
eg_paths += ['./thefile.tar.gz',
'/abs/pa.th/to/thefile.tar.gz']
for p in eg_paths:
print(Path(p).with_suffix('').stem) # prints thefile every time
from pathlib import Path
pth = Path('./thefile.tar.gz.bz.7zip')
fn = pth.name
if len(pth.suffixes) > 0:
s = pth.suffixes[0]
fn = fn.rsplit(s)[0]
# or, equivalently
fn = pth.name
for s in pth.suffixes:
fn = fn.rsplit(s)[0]
break
# or simply run the full loop
fn = pth.name
for _ in pth.suffixes:
fn = fn.rsplit('.')[0]
# In any case:
print(fn) # thefile
# Explanation
#
# pth.name -> 'thefile.tar.gz.bz.7zip'
# pth.suffixes -> ['.tar', '.gz', '.bz', '.7zip']
#
# If there may be more than two extensions, we can test for
# that case with an if statement, or simply attempt the loop
# and break after rsplitting on the first extension instance.
# Alternatively, we may even run the full loop and strip one
# extension with every pass.
# Further tests
eg_paths += ['./thefile.tar.gz.bz.7zip',
'/abs/pa.th/to/thefile.tar.gz.bz.7zip']
for p in eg_paths:
pth = Path(p)
fn = pth.name
for s in pth.suffixes:
fn = fn.rsplit(s)[0]
break
print(fn) # prints thefile every time
例如,如果扩展名可能是.tar
,.tar.gz
,.tar.gz.bz
等,则可以简单地rsplit
已知的扩展名并取第一个元素:
pth = Path('foo/bar/baz.baz/thefile.tar.gz')
fn = pth.name.rsplit('.tar')[0]
print(fn) # thefile
from pathlib import Path; print(Path("/path/to/some/file.txt").stem)
>>>file
。 - BallpointBenimport os; filepath='./readme'; dir, filename_ext = os.path.split(filepath); filename=filename_ext.rsplit('.', maxsplit=1)[0]; print(f'{dir}/{filename}') ./readme
- dlink