【问题标题】:Given a directory with sub directories, how can I find a file's path? [duplicate]给定一个带有子目录的目录,我怎样才能找到文件的路径? [复制]
【发布时间】:2019-10-26 14:24:05
【问题描述】:

假设我有以下嵌套目录结构:

my_dir
|---- dir_1
|---- dir_2
|---- dir_3
      |---- dir_4
            |---- dir_5
                  |---- dir_6
                        |---- my_file.txt

如何查看my_file.txt 是否存在于dir_3 的任何子目录中(例如dir_4dir_5dir_6),如果存在,我如何获得它的路径?目前我尝试过:

def file(name, path):
    for r, d, f in os.walk(abspath(path)):
        if name in files:
            return os.path.join(r, n)
    else:
         return 'file not found'

但是,上面的函数很奇怪。我怎样才能对 Pathlib 做同样的事情?

【问题讨论】:

  • 由于您使用的是 Python 3,因此您应该看看 pathlib 模块。
  • 你能用pathlib提出一个解决方案吗?
  • 我编辑了问题
  • 你应该花一点时间学习一下 pathlib。您可能可以使用pathlib.glob 来做您想做的事。请看stackoverflow.com/q/50714469/4014959

标签: python python-3.x directory io path


【解决方案1】:

使用 Linux shell 命令

import os
cmd = 'find my_dir -name myfile.txt'
os.system(cmd)

这将在 my_dir 目录中搜索 myfile.txt

或使用子进程模块:

import subprocess
subprocess.Popen(["find","my_dir","-name","myfile.txt"])

【讨论】:

    【解决方案2】:

    删除你的'else'分支,这样你就可以继续遍历目录树。 然后在for循环之后,你可以返回'file not found'。

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 1970-01-01
      • 2015-11-21
      • 2019-01-07
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多