首页 > 解决方案 > os.chdir() 打破了 __file__ 的 realpath 和 abspath

问题描述

该函数似乎os.chdir()改变了后续调用 forabspathrealpathof的结果__file__

一个简单的例子是:我在 Folder1 中有一个文件test.py,它看起来像这样:

 Folder1                                                            
▶ tree . 
.
├── \
├── Folder2
└── test.py

这是test.py的内容:

import os
from pathlib import Path


def test():
    pwd = os.path.dirname(os.path.realpath(__file__))
    os.chdir(f'{pwd}/Folder2')

# Path of __file__
print(os.path.realpath(__file__))
print(os.path.abspath(__file__))

test()

# Path of __file is changed !?
print(os.path.realpath(__file__))
print(os.path.abspath(__file__))

如果我运行test.py,结果如下:

 Folder1                                                             
▶ python test.py
Folder1/test.py
Folder1/test.py
Folder1/Folder2/test.py
Folder1/Folder2/test.py

如您所见,在我test()将 chdir 调用到 Folder2 后,它改变了file的 realpath 和 abspath 。为什么会这样?

我正在编写一个涉及在不同目录之间导航的程序,我应该如何避免os.chdir()破坏我的代码?我应该完全避免使用它吗?

谢谢你。

标签: pythonpython-3.x

解决方案


推荐阅读