def filename(path):"""Return file name without extension from path.
See https://docs.python.org/3/library/os.path.html"""import os.pathb = os.path.split(path)[1] # path, *filename*f = os.path.splitext(b)[0] # *file*, ext#print(path, b, f)return f
import os
def file_base_name(file_name):if '.' in file_name:separator_index = file_name.index('.')base_name = file_name[:separator_index]return base_nameelse:return file_name
def path_base_name(path):file_name = os.path.basename(path)return file_base_name(file_name)
行为规范:
>>> path_base_name('file')'file'>>> path_base_name(u'file')u'file'>>> path_base_name('file.txt')'file'>>> path_base_name(u'file.txt')u'file'>>> path_base_name('file.tar.gz')'file'>>> path_base_name('file.a.b.c.d.e.f.g')'file'>>> path_base_name('relative/path/file.ext')'file'>>> path_base_name('/absolute/path/file.ext')'file'>>> path_base_name('Relative\\Windows\\Path\\file.txt')'file'>>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')'file'>>> path_base_name('/path with spaces/file.ext')'file'>>> path_base_name('C:\\Windows Path With Spaces\\file.txt')'file'>>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')'file name with spaces'
import os
def get_filename_without_extension(file_path):file_basename = os.path.basename(file_path)filename_without_extension = file_basename.split('.')[0]return filename_without_extension
下面是一组要运行的示例:
example_paths = ["FileName","./FileName","../../FileName","FileName.txt","./FileName.txt.zip.asc","/path/to/some/FileName","/path/to/some/FileName.txt","/path/to/some/FileName.txt.zip.asc"]
for example_path in example_paths:print(get_filename_without_extension(example_path))
import osp = r"C:\Users\bilal\Documents\face Recognition python\imgs\northon.jpg"
# Get the filename only from the initial file path.filename = os.path.basename(p)
# Use splitext() to get filename and extension separately.(file, ext) = os.path.splitext(filename)
# Print outcome.print("Filename without extension =", file)print("Extension =", ext)
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
任意数量的扩展(0、1或更多)
from pathlib import Path
pth = Path('./thefile.tar.gz.bz.7zip')
fn = pth.nameif len(pth.suffixes) > 0:s = pth.suffixes[0]fn = fn.rsplit(s)[0]
# or, equivalently
fn = pth.namefor s in pth.suffixes:fn = fn.rsplit(s)[0]break
# or simply run the full loop
fn = pth.namefor _ 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.namefor s in pth.suffixes:fn = fn.rsplit(s)[0]break
print(fn) # prints thefile every time
# use pathlib. the below works with compound filetypes and normal onessource_file = 'spaces.tar.gz.zip.rar.7z'source_path = pathlib.Path(source_file)source_path.name.replace(''.join(source_path.suffixes), '')>>> 'spaces'
name = path.split('/')[-1][::-1].split('.', 1)[1][::-1]
性能:
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from pathlib import Path
In [2]: file = 'D:/ffmpeg/ffmpeg.exe'
In [3]: Path(file).stemOut[3]: 'ffmpeg'
In [4]: file.split('/')[-1][::-1].split('.', 1)[1][::-1]Out[4]: 'ffmpeg'
In [5]: %timeit Path(file).stem6.15 µs ± 433 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [6]: %timeit file.split('/')[-1][::-1].split('.', 1)[1][::-1]671 ns ± 37.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [7]: