如何在Python的os.walk中忽略.snapshot、.git这类目录?
解决Python os.walk遍历目录时忽略指定目录的问题
嘿,我来帮你搞定这个问题!首先得搞清楚os.walk的一个关键特性:遍历过程中的dirs列表是可以原地修改的——修改后,后续的遍历就会跳过那些被移除的子目录,这正是我们忽略特定目录的核心思路。
先说说你原代码里的问题:你用re.match('^\S+.snapshot$', path)去匹配当前路径,然后判断这个匹配结果是否在dirs里,这逻辑不对哦。dirs里存的是当前目录下的子目录名称(比如.snapshot),而path是当前遍历的完整路径(比如/home/me/PYTHON/OGL_TOOLS/.snapshot),所以这行判断永远不会触发,自然也没法移除目标目录。
下面给你两种可行的解决方案:
方案一:直接匹配指定目录名称
这种方法简单直接,适合忽略已知的固定目录:
import os datasource = "/home/me/PYTHON/OGL_TOOLS" def scanfolder(): # 定义要忽略的目录集合,用集合查找更快 ignore_dirs = {'.snapshot', '.git'} for path, dirs, files in os.walk(datasource): # 原地修改dirs列表,移除需要忽略的目录 # 用dirs[:] = ... 而不是dirs = ...,这样才能修改os.walk使用的原列表 dirs[:] = [dir_name for dir_name in dirs if dir_name not in ignore_dirs] depth = path.count('/') - 6 maxdepth = 2 if depth <= maxdepth: for f in files: if f.endswith('.txt'): txt_path = os.path.join(path, f) print(txt_path) # 记得补全filelog的写入逻辑,确保filelog是已打开的文件对象 # filelog.write(f'\t{txt_path} => bonne synt...\n')
方案二:用正则匹配灵活忽略目录
如果需要更灵活的匹配规则(比如忽略所有以.snapshot结尾的目录,或者多个模式),可以用正则表达式:
import os import re datasource = "/home/me/PYTHON/OGL_TOOLS" def scanfolder(): # 编译正则模式,匹配.snapshot或.git目录 ignore_pattern = re.compile(r'^\.(snapshot|git)$') for path, dirs, files in os.walk(datasource): # 过滤掉符合正则模式的目录 dirs[:] = [dir_name for dir_name in dirs if not ignore_pattern.match(dir_name)] depth = path.count('/') - 6 maxdepth = 2 if depth <= maxdepth: for f in files: if f.endswith('.txt'): txt_path = os.path.join(path, f) print(txt_path) # filelog.write(f'\t{txt_path} => bonne synt...\n')
关键注意点:
- 一定要用
dirs[:] = ...而不是直接赋值dirs = ...:前者是修改os.walk正在使用的原列表,后者只是创建了一个新的局部变量,不会影响后续的遍历。 - 你的原代码里
filelog.write语句没写完,记得补全内容,并且确保filelog是已经通过open()打开的文件对象(最好用with语句来自动管理文件)。
内容的提问来源于stack exchange,提问作者Pierre Sid
相关产品推荐
相关产品推荐

