在 python 中将相对路径添加到绝对路径
Adding a relative path to an absolute path in python
假设我有一个绝对路径和一个相对路径
abspath = os.path.abspath(__file__)
relpath = '../../folder/file'
如何在没有 ../..
的情况下 'add' 这两条路径,是否有执行此操作的模块?到目前为止我找不到任何东西。我正在考虑这样的格式:
mypath = some_module.function(abspath, relpath)
而不是
mypath = os.path.join(os.path.dirname(os.path.dirname(abspath))), folder, file)
我觉得太麻烦了
您可以 join
它们并使用 normpath:
os.path.normpath(os.path.join(abspath, relpath))
来自 normpath
文档:
Normalize a pathname by collapsing redundant separators and up-level
references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
您还可以使用 pathlib 模块,因为 Python 3.4:
from pathlib import Path
abspath = Path('/home/xxxx/yyy')
relpath = Path('../../folder/file')
(abspath / relpath).resolve()
# PosixPath('/home/xxxx')
假设我有一个绝对路径和一个相对路径
abspath = os.path.abspath(__file__)
relpath = '../../folder/file'
如何在没有 ../..
的情况下 'add' 这两条路径,是否有执行此操作的模块?到目前为止我找不到任何东西。我正在考虑这样的格式:
mypath = some_module.function(abspath, relpath)
而不是
mypath = os.path.join(os.path.dirname(os.path.dirname(abspath))), folder, file)
我觉得太麻烦了
您可以 join
它们并使用 normpath:
os.path.normpath(os.path.join(abspath, relpath))
来自 normpath
文档:
Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
您还可以使用 pathlib 模块,因为 Python 3.4:
from pathlib import Path
abspath = Path('/home/xxxx/yyy')
relpath = Path('../../folder/file')
(abspath / relpath).resolve()
# PosixPath('/home/xxxx')