【问题标题】:How to check whether a folder is a shortcut or not using python?如何使用python检查文件夹是否是快捷方式?
【发布时间】:2013-09-22 17:27:08
【问题描述】:

我正在使用 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)

【问题讨论】:

  • a) 什么是快捷方式?一条链接?符号链接? b) 您正在开发哪个操作系统?
  • @Ashwini:在 Windows 上,os.path.islink() 在给定文件夹的快捷方式(.lnk 文件)路径时返回 False
  • 在 Windows 中,快捷方式确实是一个文件,对吧?所以你需要检查内容,不是吗?
  • @Pratik:为了防止循环,您需要跟踪您已经访问过的路径以避免再次跟随它们。您可以通过在set 中跟踪它们并在跟踪遇到的任何子目录之前对其进行检查来做到这一点。

标签: python ubuntu file-io


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    它更多的评论,但对于 cmets 不起作用格式化。我不明白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
    

    【讨论】:

      【解决方案3】:

      如果您想检查(符号)链接,请查看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
      

      我刚刚使用 nautilus 以图形方式创建了一个桌面“快捷方式”,右键单击文件夹,选择“创建链接”,它只是创建了一个符号链接。上述脚本将其正确识别为链接。

      【讨论】:

      • 它不起作用,符号链接和快捷方式不同。我在快捷方式上测试了代码,但它不起作用。
      • 您能解释一下什么是“捷径”吗?
      • 这就是我所说的快捷方式link
      • 感谢您的链接,请查看我的答案的编辑。请在包含“快捷方式”的文件夹上发布ls -l,并为每个人发布os.path.islink 的结果。
      • 在文件夹上放置 ls -l 是什么意思?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多