Check if file is a symlink in python

There is a function in python to check if a given file / directory is a symbolic link? For example, for the following files, my wrapper function should return True .

 # ls -l total 0 lrwxrwxrwx 1 root root 8 2012-06-16 18:58 dir -> ../temp/ lrwxrwxrwx 1 root root 6 2012-06-16 18:55 link -> ../log 
+58
python operating-system
Jun 17 2018-12-12T00:
source share
3 answers

To determine if a directory entry is a symbolic link, use this:

os.path.islink (path)

Returns True if the path refers to a directory entry, which is a symbolic link. Always False if symbolic links are not supported.

For example, given:

 drwxr-xr-x 2 root root 4096 2011-11-10 08:14 bin/ drwxrwxrwx 1 root root 57 2011-07-10 05:11 initrd.img -> boot/initrd.img-2.. >>> import os.path >>> os.path.islink('initrd.img') True >>> os.path.islink('bin') False 
+95
Jun 17 2018-12-12T00:
source share
— -

For python 3.4 and above, you can use the Path class

 from pathlib import Path # rpd is a symbolic link >>> Path('rdp').is_symlink() True >>> Path('README').is_symlink() False 

You must be careful when using the is_symlink () method. It will return True, even if the target of the link is missing, if the named object is a symbolic link. For example (Linux / Unix):

 ln -s ../nonexistentfile flnk 

Then in your current directory run python

 >>> from pathlib import Path >>> Path('flnk').is_symlink() True >>> Path('flnk').exists() False 

The programmer must decide what he / she really wants. Python 3 seems to have renamed many classes. Maybe you should read the manual page for the Path class: https://docs.python.org/3/library/pathlib.html

+4
Sep 04 '16 at 4:39 on
source share

With no intention of inflating this topic, but I was redirected to this page when I was looking for a symbolic link to find them and convert to real files and found this script in the python tool library.

 #Source https://github.com/python/cpython/blob/master/Tools/scripts/mkreal.py import sys import os from stat import * BUFSIZE = 32*1024 def mkrealfile(name): st = os.stat(name) # Get the mode mode = S_IMODE(st[ST_MODE]) linkto = os.readlink(name) # Make sure again it a symlink f_in = open(name, 'r') # This ensures it a file os.unlink(name) f_out = open(name, 'w') while 1: buf = f_in.read(BUFSIZE) if not buf: break f_out.write(buf) del f_out # Flush data to disk before changing mode os.chmod(name, mode) mkrealfile("/Users/test/mysymlink") 
0
Nov 19 '17 at 8:36
source share



All Articles