Check if file is symlink in python

前端 未结 3 1380
甜味超标
甜味超标 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")
    

提交回复
热议问题