我可以使用哪个Python库从路径中提取文件名,而不管操作系统或路径格式是什么?
例如,我希望所有这些路径都返回c
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c发布于 2016-11-28 21:33:14
这是一个仅支持regex的解决方案,它似乎适用于任何操作系统上的任何OS路径。
不需要其他模块,也不需要预处理:
import re
def extract_basename(path):
"""Extracts basename of a given path. Should Work with any OS Path on any OS"""
basename = re.search(r'[^\\/]+(?=[\\/]?$)', path)
if basename:
return basename.group(0)
paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
'a/b/../../a/b/c/', 'a/b/../../a/b/c']
print([extract_basename(path) for path in paths])
# ['c', 'c', 'c', 'c', 'c', 'c', 'c']
extra_paths = ['C:\\', 'alone', '/a/space in filename', 'C:\\multi\nline']
print([extract_basename(path) for path in extra_paths])
# ['C:', 'alone', 'space in filename', 'multi\nline']更新:
如果您只想要一个潜在的文件名(如果存在)(例如,/a/b/是一个目录,c:\windows\也是一个目录),请将正则表达式更改为:r'[^\\/]+(?![\\/])$'。对于“正则表达式挑战”,这会将某种斜杠的正向前视更改为负向前视,从而导致以该斜杠结尾的路径名不返回任何内容,而不是返回路径名中的最后一个子目录。当然,不能保证潜在的文件名确实指的是文件,因此需要使用os.path.is_dir()或os.path.is_file()。
这将匹配如下:
/a/b/c/ # nothing, pathname ends with the dir 'c'
c:\windows\ # nothing, pathname ends with the dir 'windows'
c:hello.txt # matches potential filename 'hello.txt'
~it_s_me/.bashrc # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
# that is obviously a dir. os.path.is_dir()
# should be used to tell us for sure可以对正则表达式进行here测试。
https://stackoverflow.com/questions/8384737
复制相似问题