Python os.path.basename() 和 os.path.dirname() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22272003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between os.path.basename() and os.path.dirname()?
提问by user1429210
What is the difference between os.path.basename()and os.path.dirname()?
os.path.basename()和 和有os.path.dirname()什么区别?
I already searched for answers and read some links, but didn't understand. Can anyone give a simple explanation?
我已经搜索了答案并阅读了一些链接,但不明白。谁能给一个简单的解释?
采纳答案by Breno Teixeira
Both functions use the os.path.split(path)function to split the pathname pathinto a pair; (head, tail).
两个函数都使用该os.path.split(path)函数将路径名拆分path为一对;(head, tail).
The os.path.dirname(path)function returns the head of the path.
该os.path.dirname(path)函数返回路径的头部。
E.g.: The dirname of '/foo/bar/item'is '/foo/bar'.
例如: 的目录名'/foo/bar/item'是'/foo/bar'。
The os.path.basename(path)function returns the tail of the path.
该os.path.basename(path)函数返回路径的尾部。
E.g.: The basename of '/foo/bar/item'returns 'item'
例如:'/foo/bar/item'返回的基本名称'item'
From: http://docs.python.org/2/library/os.path.html#os.path.basename
来自:http: //docs.python.org/2/library/os.path.html#os.path.basename
回答by Umar Dastgir
To summarize what was mentioned by Breno above
总结上面 Breno 提到的内容
Say you have a variable with a path to a file
假设您有一个带有文件路径的变量
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)returns the string 'myfile.py'
os.path.basename(path)返回字符串 'myfile.py'
and
和
os.path.dirname(path)returns the string '/home/User/Desktop'(without a trailing slash '/')
os.path.dirname(path)返回字符串'/home/User/Desktop'(没有尾部斜杠'/')
These functions are used when you have to get the filename/directory name given a full path name.
当您必须获取给定完整路径名的文件名/目录名时,将使用这些函数。
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'you just have myfile.py), os.path.dirname(path)returns an empty string.
如果文件路径只是文件名(例如,而不是path = '/home/User/Desktop/myfile.py'您只有myfile.py),则os.path.dirname(path)返回一个空字符串。

