How to get a symbolic path instead of the real path?

Suppose I have a path named:

/this/is/a/real/path 

Now I create a symbolic link for it:

 /this/is/a/link -> /this/is/a/real/path 

and then I put the file in this path:

 /this/is/a/real/path/file.txt 

and cd with a symbolic path name:

 cd /this/is/a/link 

now the pwd command will return the link name:

 > pwd /this/is/a/link 

and now I want to get the absolute file.txt path as:

 /this/is/a/link/file.txt 

but with python os.abspath() or os.realpath() , they all return the real path ( /this/is/a/real/path/file.txt ), which is not what I want.

I also tried subprocess.Popen('pwd') and sh.pwd() , but also got the real path instead of the symlink path.

How can I get a symbolic absolute path using python?

Update

OK, I read the pwd source code to get the answer.

It's pretty simple: just get the pwd environment variable.

This is my own abspath to satisfy my requirement:

 def abspath(p): curr_path = os.environ['PWD'] return os.path.normpath(os.path.join(curr_path, p)) 
+7
python symlink
source share
3 answers

The difference between os.path.abspath and os.path.realpath is that os.path.abspath does not allow symbolic links, so this should be exactly what you are looking for. I:

 /home/user$ mkdir test /home/user$ mkdir test/real /home/user$ mkdir test/link /home/user$ touch test/real/file /home/user$ ln -s /home/user/test/real/file test/link/file /home/user$ ls -lR test test: d... link d... real test/real: -... file test/link: l... file -> /home/user/test/real/file /home/user$ python ... python 3.3.2 ... >>> import os >>> print(os.path.realpath('test/link/file')) /home/user/test/real/file >>> print(os.path.abspath('test/link/file')) /home/user/test/link/file 

So you go. How do you use os.path.abspath , what do you say that it resolves your symbolic link?

+15
source share

You can do this to go through the directory:

 for root, dirs, files in os.walk("/this/is/a/link"): for file in files: os.path.join(root, file) 

Thus, you will get the path to each file with a prefix of the name of the symbolic link instead of the real one.

0
source share

from python document 2.7.3:

os.path.abspath (path) ΒΆ

 Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to normpath(join(os.getcwd(), path)). 

os.getcwd () will return the real path. eg.

 /home/user$ mkdir test /home/user$ cd test /home/user/test$ mkdir real /home/user/test$ ln -s real link /home/user/test$ cd link /home/user/test/link$ python >>> import os >>> os.getcwd() '/home/user/test/real' >>> os.path.abspath("file") '/home/user/test/real/file' >>> os.path.abspath("../link/file") '/home/user/test/link/file' 

or

 /home/user/test/link$ cd .. /home/user/test$ python >>> import os >>> os.path.abspath("link/file") '/home/user/test/link/file' 
-one
source share

All Articles