我有以下代码:
os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../test")
path.append(os.getcwd())
os.chdir(os.path.dirname(os.path.realpath(__file__)))
应该将 /../test
添加到 python 路径,它确实这样做了,然后使用 PyDev 在 eclipse 上顺利运行。
但是当我从控制台第二个 os.chdir 午餐同一个应用程序时做错了,实际上错误的是 os.path.realpath(__file__)
cus 它返回 ../test/myFile.py
而不是 ../originalFolder/myFile.py
。当然,我可以通过使用固定的 os.chdir("../originalFolder")
来解决这个问题,但这对我来说似乎有点不对,但这适用于 eclipse 和控制台。
附言我正在使用 os.getcwd()
实际上是因为我想确保没有添加这样的文件夹,否则我根本不需要切换目录
那么我的方法有什么问题还是我搞砸了什么?还是什么? :)
提前致谢! :)
最佳答案
看看__file__
的值是什么。它不包含脚本的绝对路径,它是来自命令行的值,因此它可能类似于“./myFile.py”或“myFile.py”。此外,realpath() 不会使路径成为绝对路径,因此在不同目录中调用 realpath("myFile.py") 仍将返回“myFile.py”。
我认为你应该这样做:
import os.path
script_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(script_dir, '..', 'test')
print(os.getcwd())
os.chdir(target_dir)
print(os.getcwd())
os.chdir(script_dir)
print(os.getcwd())
在我的电脑 (Windows) 上我有这样的结果:
e:\parser>c:\Python27\python.exe .\rp.py
e:\parser
e:\test
e:\parser
e:\parser>c:\Python27\python.exe ..\parser\rp.py
e:\parser
e:\test
e:\parser
注意:如果您关心兼容性(您不喜欢奇怪的路径错误),您应该在组合路径时使用os.path.join()。
注意:我知道我的解决方案非常简单(记住绝对路径),但有时最简单的解决方案是最好的。
关于python os.path.realpath 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887259/