Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python os.path.realpath not working properly

I have 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__)))

Which should add /../test to python path, and it does so, and it all runs smoothly afterwards on eclipse using PyDev.

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

P.S. I'm using os.getcwd() actually because I want to make sure there isn't such folder already added, otherwise I wouldn't have to switch dir's at all

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

Thanks in advance! :)

like image 747
jj. Avatar asked Mar 27 '12 09:03

jj.


People also ask

What does OS path Realpath () do?

path. realpath() method in Python is used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path.

What is OS path dirname (__ FILE __?

C = os.path.abspath(os.path.dirname(__file__)) # C is the absolute path of the directory where the program resides. You can see the many values returned from these here: import os. print(__file__)

What is the use of OS path Dirname file in this?

path. dirname() method in Python is used to get the directory name from the specified path.

What is OS path Abspath Python?

The os. path is a built-in Python module that provides a range of useful functions to change files and directories.


1 Answers

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.

like image 157
Tupteq Avatar answered Sep 19 '22 23:09

Tupteq