检查文件是否是python中的符号链接

时间:2012-06-17 02:03:57

标签: python operating-system

在python中,是否有一个函数来检查给定的文件/目录是否是符号链接?例如,对于以下文件,我的包装函数应该返回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

3 个答案:

答案 0 :(得分:113)

要确定目录条目是否为符号链接,请使用以下命令:

  

os.path.islink(path)

     

如果path引用符号的目录条目,则返回True   链接。如果不支持符号链接,则始终为False。

例如,给定:

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

答案 1 :(得分:7)

对于python 3.4及更高版本,您可以使用Path类

from pathlib import Path


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

使用is_symlink()方法时必须小心。只要命名对象是符号链接,它就会返回True,即使链接的目标也不存在。例如(Linux / Unix):

ln -s ../nonexistentfile flnk

然后,在当前目录中启动python

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

程序员必须决定他/她真正想要的是什么。 Python 3似乎已经重命名了很多类。阅读Path类的手册页可能是值得的:https://docs.python.org/3/library/pathlib.html

答案 2 :(得分:3)

我没有打算讨论这个话题,但我被重定向到这个页面,因为我正在寻找符号链接来查找它们并将它们转换为真实文件并在python工具库中找到这个脚本。

#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")