python os.path.realpath not working properly

本小妞迷上赌 提交于 2019-12-04 08:37:34
Tupteq

Take a look what is value of __file__. It doesn't contain absolute path to your script, it's a value from command line, so it may be something like "./myFile.py" or "myFile.py". Also, realpath() doesn't make path absolute, so realpath("myFile.py") called in different directory will still return "myFile.py".

I think you should do ssomething like this:

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())

On my computer (Windows) I have result like that:

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

Note: If you care for compatibility (you don't like strange path errors) you should use os.path.join() whenever you combine paths.

Note: I know my solution is dead simple (remember absolute path), but sometimes simplest solutions are best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!