python - os.chdir() 打破了 __file__ 的 realpath 和 abspath
问题描述
该函数似乎os.chdir()
改变了后续调用 forabspath
和realpath
of的结果__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()
破坏我的代码?我应该完全避免使用它吗?
谢谢你。
解决方案
推荐阅读
- php - 是否有挂钩或插件可以从 woocommerce 优惠券中排除某些产品标签?
- prometheus - 如何查询具有特定值和时间偏移的 Prometheus 向量?
- jquery - 如何使用 laravel 在数据表中显示数据库中的记录
- python - linux - 通过 dbus 停止 systemd-networkd
- c++ - 在其他函数或循环中构造 lambda 时是否存在性能问题?
- spring - 在具有名称的 DispatcherServlet 中找不到具有 URI 的 HTTP 请求的映射
- c# - 带有 DataReader 的存储过程
- python - Python 字典操作
- sql - 在 Oracle/Sqlplus 中进行图形/节点跟踪的最佳方法?
- android - CardView:如何在保持半径的同时添加渐变背景