Python os.path.realpath not working properly

I have the following code:

os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../test") path.append(os.getcwd()) os.chdir(os.path.dirname(os.path.realpath(__file__))) 

What should add /../test to the python path, and it does this, and it all runs smoothly after that on eclipse using PyDev.

But when I dine the same application from the console, the second os.chdir does something wrong, actually the wrong thing is in the os.path.realpath(__file__) cus, it returns ../test/myFile.py instead ../originalFolder/myFile.py . Of course, I can fix this using fixed os.chdir("../originalFolder") , but this seems a bit wrong to me, but it works on both eclipse and the console.

PS I os.getcwd() use os.getcwd() because I want to make sure that this folder is not already added, otherwise I would not need to switch from dir at all

So is something wrong with my approach, or have I messed up something? or what? :)

Thanks in advance!:)

+4
source share
1 answer

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.

+6
source

Source: https://habr.com/ru/post/1403626/


All Articles