python - 您可以为 abspath 设置 cwd 吗?

标签 python path python-3.4

我正在尝试将相对路径扩展为绝对路径。相对路径有时会包含一个 . ,它需要从当前工作目录中扩展出来。我想知道 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'

关于python - 您可以为 abspath 设置 cwd 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30655427/

相关文章:

python - 从同一目录导入python文件时导入错误

android - Ndk-cygwin 路径特定问题

java - 如何使用 Java 访问安装在 Windows 上的驱动器?

python - 我不知道如何在 Python 中创建一个调用我的函数的字典

python - 具有固定队列大小或缓冲区的 multiprocessing.Pool.imap_unordered?

python - 在此示例中, `eval()` 如何不是 'dangerous'

python - 在 numpy 中总结 ndarray 同时最小化浮点不准确性的最有效方法是什么?

python - Matplotlib 有时会向图表添加比应有的更多绘图

python - 终端上 Python 的着色异常

c# - 在路径 C# 中同时前后导航