繁体   English   中英

如何使用python检查文件夹是否为快捷方式?

[英]How to check whether a folder is a shortcut or not using python?

我正在使用python制作一个简单的程序,该程序从用户那里接收两个输入:-filename,这是用户要搜索的文件名。 pathname是用户要在其中搜索文件的路径。 我在代码中使用os模块。 但是,我希望我的程序不应该在快捷方式中搜索文件。 因此,有没有一种方法可以检查文件夹是否为快捷方式? 我在下面发布我的函数的定义:

def searchwithex(path, filen):
    global globalFileVal
    global globalFileList
    global count
    dirCounter = checkdir(path)  # checks whether the path is accesible or not.
    if dirCounter == True:
        topList = listdir(path)
        for items in topList:
            count += 1
            if filen == items:
                globalFileVal = path +'/' + items
                globalFileList.append(globalFileVal)
            items = path +  '/' + items
            if os.path.isdir(items): # checks whether the given element is a #file or a directory.
                counter = searchwithex(items, filen)

在Windows上,链接(快捷方式)的文件类型为".lnk"因此您可以尝试fn.endswith(".lnk") ,这些快捷方式文件将返回True 至少在Windows上, os.path.islink()只能看到一个文件,这与其他具有真正链接的操作系统(例如linux)不同。

如果要检查(符号)链接,请查看os.path.islink是否满足您的需求。

$ touch a
$ ln -s a b
$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path as _
>>> _.islink ('a')
False
>>> _.islink ('b')
True

我刚刚用鹦鹉螺图形化地创建了一个桌面“快捷方式”,右键单击文件夹,选择了“创建链接”,它只是创建了一个符号链接。 上面的脚本将其正确标识为链接。

它有更多注释,但对于注释无法使用格式。 我不明白什么是shorcut但我有希望,下面将对您有所帮助:

In [1]: import os
In [2]: files = os.listdir("./tmp/11");
In [3]: print files
['mylog', 'testfile1', 'test.py', 'testfile0', 'test.sh', 'myflags', 'testfile2']
In [4]: True if "test.py" in files else False
True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM