2016年1月18日 星期一

[ Python 常見問題 ] Extract file name from path, no matter what the os/path format

Source From Here
Question
Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me '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

How-To
Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail. Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.
>>> import ntpath
>>> ntpath.basename("a/b/c")
'c'
>>> ntpath.basename("a\\b\\c")
'c'

Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:
>>> path = "a\\b\\c\\"
>>> ntpath.basename(path)
''
>>> head, tail = ntpath.split(path)
>>> head
'a\\b\\c'
>>> tail
''
>>> def path_leaf(path):
... head, tail = ntpath.split(path)
... return tail or ntpath.basename(head)
...
>>> path_leaf("a\\b\\c")
'c'
>>> path_leaf(path)
'c'
>>> 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']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...