Check if file is symlink in python

前端 未结 3 1375
甜味超标
甜味超标 2020-12-01 11:26

In python, is there a function to check if a given file/directory is a symlink ? For example, for the below files, my wrapper function should return True.

相关标签:
3条回答
  • 2020-12-01 12:04

    Without the intention to bloat this topic, but I was redirected to this page as I was looking for symlink's to find them and convert them to real files and found this script within the python tools 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's a symlink
        f_in = open(name, 'r') # This ensures it's 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 讨论(0)
  • 2020-12-01 12:07

    To determine if a directory entry is a symlink use this:

    os.path.islink(path)

    Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported.

    For instance, 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
    
    0 讨论(0)
  • 2020-12-01 12:20

    For python 3.4 and up, 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 have to be careful when using the is_symlink() method. It will return True even the target of the link is non-existent as long as the the named object is a symlink. For example (Linux/Unix):

    ln -s ../nonexistentfile flnk
    

    Then, in your current directory fire up python

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

    The programmer has to decide what he/she realy wants. Python 3 seems to have renamed a lots of classes. It might be worthwhile to read the manual page for the Path class: https://docs.python.org/3/library/pathlib.html

    0 讨论(0)
提交回复
热议问题