在文件夹结构中爬行的os.walk

2024-05-08 20:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码可以查看单个文件夹并提取文件。 但现在文件夹结构已更改,我需要在文件夹中搜索匹配的文件。

旧代码是什么样子

GSB_FOLDER = r'D:\Games\Gratuitous Space Battles Beta' 

def get_module_data():
    module_folder = os.path.join(GSB_FOLDER, 'data', 'modules')

    filenames = [os.path.join(module_folder, f) for f in
                  os.listdir(module_folder)]

    data = [parse_file(f) for f in filenames]

    return data

但现在文件夹结构已更改为如下所示

  • GSB U文件夹\数据\模块
    • \文件夹1 \数据\模块
    • \文件夹2 \数据\模块
    • \文件夹3 \数据\模块

其中folder1、2或3可以是任何文本字符串

我该如何重写上面的代码来完成这个任务。。。 有人告诉我关于os.walk的事,但我只是在学习Python。。。所以感谢你的帮助


Tags: 模块文件数据path代码文件夹dataos
3条回答

walk是一个很好的简单的方法,它可以获取你传递的目录中所有内容的目录结构

在你的例子中,你可以这样做:

for dirpath, dirnames, filenames in os.walk("...GSB_FOLDER"):
  #whatever you want to do with these folders
  if "/data/modules/" in dirpath:
    print dirpath, dirnames, filenames

试一试,应该是相当不言自明的工作方式。。。

只要调用os.walk就不会有太大的变化,它将递归地遍历目录并返回文件,例如

for root, dirs, files in os.walk('/tmp'):
    if os.path.basename(root) != 'modules':
        continue
    data = [parse_file(os.path.join(root,f)) for f in files]

在这里,我只检查名为“modules”的文件夹中的文件,您可以将该检查更改为执行其他操作,例如,在某处具有模块的路径root.find('/modules') >= 0

你可以像@Anurag has detailed那样使用os.walk,也可以尝试我的小型^{}库:

data = [parse_file(f) for f in pathfinder.find(GSB_FOLDER), just_files=True]

相关问题 更多 >