How to test if a file is a symbolic link?

P

Peng Yu

'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"
 
S

Steven D'Aprano

'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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top