How to test if a file is a symbolic link?

tec technic.tec at gmail.com
Thu Oct 29 04:47:14 CET 2009


On 2009-10-29 11:19, 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"

Use os.lstat instead of os.stat to prevent following symbolic links.

Or more directly, use os.path.islink()




More information about the Python-list mailing list