Вопрос

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:

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.

How can I do this?

Это было полезно?

Решение 3

Lately, I discovered 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()

Другие советы

You can use normpath, realpath or 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

consider to use os.path.abspath this will evaluate the absolute path

or One can use os.path.normpath this will return the normalized path (Normalize path, eliminating double slashes, etc.)

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

os.path.abspath("../../my_dir")

os.path.normpath should be used if you are interested in the relative path.

>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'

Other references for handling with file paths:

  • pathlib - Object-oriented filesystem paths
  • os.path— Common pathname manipulations
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top