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

標籤

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


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!