【问题标题】:How to find the path of any specific file, "just like search", through python如何通过python找到任何特定文件的路径,“就像搜索一样”
【发布时间】:2015-10-09 10:27:46
【问题描述】:

我正在运行一个脚本,作为一项任务,我下载了一个文件(不是从 python:假设用户从浏览器下载了一个 txt 文件),并且用户可以在任何地方下载它。在下一步中,我想要一个脚本来找到该文件并给我加载文件的路径.. 我试图从 python 模仿以下 osacript

cmd1 = "find ~ -type f -name \"sometextfile.txt\""
p = subprocess.Popen(cmd1.strip().split(" "), stdout = subprocess.PIPE)
output, err = p.communicate()
print output

但它说找不到“find:~”

有什么方法可以实现我的目标吗?

【问题讨论】:

    标签: python file-search


    【解决方案1】:

    你可以这样使用glob

    import glob
    
    file_ = glob.glob("sometextfile*")[0]
    

    【讨论】:

      【解决方案2】:

      您可以遍历所需目录并检查是否遇到文件:

      import os
      
      def find_file(root_path, searched_file):
          for root, dirs, filenames in os.walk(root_path):
              if searched_file in filenames:
                  return os.path.join(root, searched_file)
      
      output = find_file(os.environ['HOME'], 'sometextfile.txt')  # or whatever base directory
      

      【讨论】:

      • 例如,如果我的文件(list.html)位于 Documents 目录的某个子目录中。当我使用“list.html”代替“sometextfile.txt”运行上一个脚本时,我总是得到以下结果> /Users/saurabh.datta/Desktop/list.html 这不是我的目录
      • 您确定您的桌面上没有list.html 文件吗?即使您可能在另一个目录中有一个文件,此函数也仅返回遍历磁盘时遇到的第一个文件的路径。如果您正在寻找/Users/saurabh.datta/Example/list.html,那么运气不好,DesktopExample 之前。要么确保文件名在目录中是唯一的,要么将return 更改为yield,这样你就可以获得多个结果(使用list(find_file(..., ...)))。
      猜你喜欢
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2017-05-25
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多