Python 使用 os.path.join 加入当前目录和父目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17295086/
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
Python joining current directory and parent directory with os.path.join
提问by Lewistrick
I want to do join the current directory path and a relative directory path goal_dir
somewhere up in the directory tree, so I get the absolute path to the goal_dir
. This is my attempt:
我想加入当前目录路径和goal_dir
目录树中某处的相对目录路径,所以我得到了goal_dir
. 这是我的尝试:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
Now, if the current directory is C:/here/I/am/
, it joins them as C:/here/I/am/../../my_dir
, but what I want is C:/here/my_dir
. It seems that os.path.join
is not that intelligent.
现在,如果当前目录是C:/here/I/am/
,它将它们连接为C:/here/I/am/../../my_dir
,但我想要的是C:/here/my_dir
. 好像os.path.join
没有那么聪明。
How can I do this?
我怎样才能做到这一点?
采纳答案by Lewistrick
Lately, I discovered pathlib.
最近,我发现了 pathlib。
from pathlib import Path
cwd = Path.cwd()
goal_dir = cwd.parent.parent / "my_dir"
Or, using the file of the current script:
或者,使用当前脚本的文件:
cwd = Path(__file__).parent
goal_dir = cwd.parent.parent / "my_dir"
In both cases, the absolute path in simplified form can be found like this:
在这两种情况下,都可以像这样找到简化形式的绝对路径:
goal_dir = goal_dir.resolve()
回答by alecxe
You can use normpath, realpathor abspath:
您可以使用normpath、realpath或abspath:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir) # prints C:/here/my_dir
print os.path.realpath(goal_dir) # prints C:/here/my_dir
print os.path.abspath(goal_dir) # prints C:/here/my_dir
回答by oleg
consider to use os.path.abspath
this will evaluate the absolute path
考虑使用os.path.abspath
这将评估绝对路径
or One can use os.path.normpath
this will return the normalized path (Normalize path, eliminating double slashes, etc.)
或者一个可以使用os.path.normpath
这将返回规范化路径(规范化路径,消除双斜杠等)
One should pick one of these functions depending on requirements
应根据要求选择这些功能之一
In the case of abspath
In Your example, You don't need to use os.path.join
在abspath
In Your example的情况下,您不需要使用os.path.join
os.path.abspath("../../my_dir")
os.path.normpath
should be used if you are interested in the relative path.
os.path.normpath
如果您对相对路径感兴趣,则应使用。
>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'
Other references for handling with file paths:
处理文件路径的其他参考资料: