See what __file__ . It does not contain an absolute path to your script, it is a value from the command line, so it can be something like "./myFile.py" or "myFile.py". In addition, realpath () does not make the path absolute, so realpath ("myFile.py"), called in another directory, will still return "myFile.py".
I think you should do something 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 the result:
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 need compatibility (you don't like strange path errors), you should use os.path.join () when combining paths.
Note. I know that my solution is dead simple (remember the absolute path), but sometimes the simplest solutions are best.
source share