简体   繁体   English

Python 使用 os.path.join 加入当前目录和父目录

[英]Python joining current directory and parent directory with os.path.join

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 .我想加入当前目录路径和目录树中某个位置的相对目录路径goal_dir ,所以我得到了goal_dir的绝对路径。 This is my attempt:这是我的尝试:

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 .现在,如果当前目录是C:/here/I/am/ ,它将它们连接为C:/here/I/am/../../my_dir ,但我想要的是C:/here/my_dir It seems that os.path.join is not that intelligent.似乎os.path.join不是那么聪明。

How can I do this?我怎样才能做到这一点?

You can use normpath , realpath or abspath :您可以使用normpathrealpathabspath

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

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.joinabspath的情况下,在您的示例中,您不需要使用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:处理文件路径的其他参考资料:

  • pathlib - Object-oriented filesystem paths pathlib - 面向对象的文件系统路径
  • os.path — Common pathname manipulations os.path — 常见的路径名操作

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM