【问题标题】:Python: For each directory in the working directory go into that directory and get the name of the directoryPython:对于工作目录中的每个目录,进入该目录并获取目录的名称
【发布时间】:2016-12-01 15:07:51
【问题描述】:

我需要编写一个脚本来遍历目录中的所有目录。它应该进入每个目录,获取其名称并将其保存到变量中并返回,然后循环。

    for dir in os.walk(exDir):
        path = dir
        os.chdir(path)
        source = #dir trimmed to anything after the last /
        os.chdir("..")
    loops

它需要进入目录来做上面没有提到的其他事情。我才刚刚开始使用 Python,并且在最后一天左右一直被困在这个问题上。

【问题讨论】:

标签: python python-3.x navigation directory


【解决方案1】:

对于 for 循环的每次迭代,dir 是格式为 (filepath, subdirectories, files) 的元组。因此dir[0] 会给你文件路径。

听起来您只想在 exDir 中递归地为每个文件夹 os.chdir 在这种情况下,以下将起作用:

for dir in os.walk(exDir):
    os.chdir(dir[0])
    ...

【讨论】:

  • 谢谢。似乎是我需要的。
猜你喜欢
  • 2011-02-11
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多