【问题标题】:Getting sub directories and files using python使用python获取子目录和文件
【发布时间】:2012-06-04 22:47:34
【问题描述】:

获取驱动器的子目录(包括其中的文件)的最佳方法是什么?最好使用os.listdir() 并通过检查文件中是否包含'.' 来过滤掉目录?

任何想法都会有所帮助,我更希望我只使用标准库来完成这项任务。

【问题讨论】:

  • 你已经给出了一个想法,你为什么不尝试呢?如果有,为什么它不起作用?
  • os.path.isdir(full_path) 会告诉你某事是否是一个目录。

标签: python directory python-2.7 directory-structure


【解决方案1】:

看看os.walk(),它允许您访问每个目录并获取您访问的每个目录的文件列表和子目录列表。

这是你只能下降一个级别的方法:

for root, dirs, files in os.walk(path):
    # do whatever you want to with dirs and files
    if root != path:
        # one level down, modify dirs in place so we don't go any deeper
        del dirs[:]

【讨论】:

  • OP 似乎只想往下一层。
猜你喜欢
  • 2014-10-04
  • 2013-11-28
  • 2014-11-10
  • 2011-02-23
  • 2021-04-03
  • 2020-08-22
  • 1970-01-01
  • 2013-07-23
  • 2022-07-27
相关资源
最近更新 更多