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

"/path/to/some/file.txt"  →  "file"

当前回答

我们可以做一些简单的拆分/弹出魔术,如图所示(https://stackoverflow.com/a/424006/1250044),以提取文件名(考虑windows和POSIX的差异)。

def getFileNameWithoutExtension(path):
  return path.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

其他回答

导入操作系统

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

这将返回不带扩展名的文件名(C:\Users\Public\Videos\Sample Videos\wildlife)

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

现在,您可以使用

os.path.basename(temp)   #this returns just the filename (wildlife)

其他方法不会删除多个扩展。有些文件名没有扩展名也有问题。这段代码处理这两个实例,在Python2和Python3中都可以使用。它从路径中获取基名称,将值拆分为点,并返回第一个值,即文件名的初始部分。

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))

在任何情况下,打印的值为:

FileName

我没有仔细看,但我没有看到任何人使用正则表达式解决这个问题。

我将问题解释为“给定路径,返回不带扩展名的基名称。”

e.g.

“path/to/file.json”=>“文件”

“path/to/my.file.json”=>“my.file”

在Python 2.7中,我们仍然没有pathlib。。。

def get_file_name_prefix(file_path):
    basename = os.path.basename(file_path)

    file_name_prefix_match = re.compile(r"^(?P<file_name_pre fix>.*)\..*$").match(basename)

    if file_name_prefix_match is None:
        return file_name
    else:
        return file_name_prefix_match.group("file_name_prefix")
get_file_name_prefix("path/to/file.json")
>> file

get_file_name_prefix("path/to/my.file.json")
>> my.file

get_file_name_prefix("path/to/no_extension")
>> no_extension

您可以通过以下方式制作自己的产品:

>>> 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

请参阅下面的其他答案来解决这个问题。

改进@spinup答案:

fn = pth.name
for s in pth.suffixes:
    fn = fn.rsplit(s)[0]
    break
    
print(fn)      # thefile 

这也适用于没有扩展名的文件名