How to test if a file is a symbolic link?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Oct 28 23:49:18 EDT 2009


On Wed, 28 Oct 2009 22:19:55 -0500, Peng Yu wrote:

> 'symbolic_link' is a symbolic link in the current directory. I run
> 'python main.py', but it does not return me anything. I want to check if
> a file is a symbolic link. I'm wondering what is the correct way to do
> so?
> 
> $cat main.py
> import stat
> import os
> 
> st = os.stat('symbolic_link')
> if stat.S_ISLNK(st.st_mode):
>   print "Hello"


I believe os.stat follows links, so you're testing if the original file 
is a symbolic link.

You want to use os.lstat, or the os.path.islink() function.


-- 
Steven



More information about the Python-list mailing list