[英]Check if file is symlink in python
In python, is there a function to check if a given file/directory is a symlink ?在python中,是否有一个函数来检查给定的文件/目录是否是一个符号链接? For example, for the below files, my wrapper function should return
True
.例如,对于下面的文件,我的包装函数应该返回
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
To determine if a directory entry is a symlink use this:要确定目录条目是否是符号链接,请使用以下命令:
os.path.islink(path)
os.path.islink(路径)
Return True if path refers to a directory entry that is a symbolic link.
如果路径指的是作为符号链接的目录条目,则返回 True。 Always False if symbolic links are not supported.
如果不支持符号链接,则始终为 False。
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
For python 3.4 and up, you can use the Path class对于 python 3.4 及更高版本,您可以使用 Path 类
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.使用 is_symlink() 方法时必须小心。 It will return True even the target of the link is non-existent as long as the the named object is a symlink.
只要命名对象是符号链接,即使链接的目标不存在,它也会返回 True。 For example (Linux/Unix):
例如(Linux/Unix):
ln -s ../nonexistentfile flnk
Then, in your current directory fire up python然后,在您当前的目录中启动 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.
Python 3 似乎重命名了很多类。 It might be worthwhile to read the manual page for the Path class: https://docs.python.org/3/library/pathlib.html
阅读 Path 类的手册页可能是值得的: https : //docs.python.org/3/library/pathlib.html
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.无意膨胀这个话题,但我被重定向到这个页面,因为我正在寻找符号链接来找到它们并将它们转换为真实文件,并在 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.