Skip to main content
 首页 » 编程设计

python之您可以为 abspath 设置 cwd 吗

2025年05月04日8jillzhang

我正在尝试将相对路径扩展为绝对路径。相对路径有时会包含一个 . ,它需要从当前工作目录中扩展出来。我想知道 Python 中的任何标准函数是否接受 cwd kwarg,就像 subprocess.popen 那样。

最优解

abs_path = os.path.abspath(rel_path, cwd=special_cwd) 

当前解决方案

# Capture current working directory 
previous_cwd = os.getcwd() 
 
# Change to the new working directory 
os.chdir(new_cwd) 
 
# Convert relative path to absolute path 
abs_path = os.path.abspath(rel_path) 
 
# Change back to previous working directory 
os.chdir(previous_cwd) 

目前的解决方案似乎很笨拙,有没有更好的方法来实现这一目标?

请您参考如下方法:

The current solution seems clunky, is there a better way to accomplish this?

您可以将自己的代码编写为 context manager更改目录然后更改回来:

>>> from contextlib import contextmanager 
 
>>> @contextmanager 
... def cwd(path): 
...     from os import getcwd, chdir 
...     cwd = getcwd() 
...     chdir(path) 
...     yield 
...     chdir(cwd) 

那么实际的代码看起来会更清晰:

>>> os.getcwd() 
'/home/user' 
 
>>> with cwd('/usr/share'): 
...     print(os.path.abspath('./test')) 
...  
/usr/share/test 
 
>>> os.getcwd() 
'/home/user'