Python 3.8.2 (default, Mar 13 2020, 10:14:16)[GCC 9.3.0] on LinuxType "help", "copyright", "credits" or "license" for more information.>>> import os>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.>>> os.path.basename(filepath)'C:\\my\\path\\to\\file.txt'
a.rstrip("\\\\" if a.count("/") == 0 else '/').split("\\\\" if a.count("/") == 0 else '/')[-1]
示例代码:
b = ['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']
for a in b:
print (a, a.rstrip("\\" if a.count("/") == 0 else '/').split("\\" if a.count("/") == 0 else '/')[-1])
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/ # 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
import posixpath # to generate unix pathsfrom pathlib2 import PurePath, PureWindowsPath, PurePosixPath
def path2unix(path, nojoin=True, fromwinpath=False):"""From a path given in any format, converts to posix path formatfromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)"""if not path:return pathif fromwinpath:pathparts = list(PureWindowsPath(path).parts)else:pathparts = list(PurePath(path).parts)if nojoin:return pathpartselse:return posixpath.join(*pathparts)
用法:
In [9]: path2unix('lala/lolo/haha.dat')Out[9]: ['lala', 'lolo', 'haha.dat']
In [10]: path2unix(r'C:\lala/lolo/haha.dat')Out[10]: ['C:\\', 'lala', 'lolo', 'haha.dat']
In [11]: path2unix(r'C:\lala/lolo/haha.dat') # works even with malformatted cases mixing both Windows and Linux path separatorsOut[11]: ['C:\\', 'lala', 'lolo', 'haha.dat']
使用您的测试用例:
In [12]: testcase = 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']
In [14]: for t in testcase:...: print(path2unix(t)[-1])...:...:ccccccc
import os as osimport glob as globpath = 'mypath'file_list= []for file in glob.glob(path):data_file_list = os.path.basename(file)file_list.append(data_file_list)