You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将预设文件列表与os.walk生成的文件列表对比验证?

文件与文件夹自动化验证代码问题

需求

编写自动化验证代码,遍历目标文件夹,检查必填文件是否存在,若缺失则输出 Required file {file} is missing at {location}。

目标文件夹结构

| main folder # 可自定义名称,存放待检查的文件夹
->| project folder # 待检查的项目文件夹
-->| vocab subfolder
--->| custom.xsd
--->| strict.xsd
--->| loose.xsd
-->| unique subfolder
--->| strict.xsd
--->| loose.xsd
-->| extended subfolder
--->| strict.xsd
-->| datatypes.dtd
-->| xml.xsd
-->| anyElement.xsd
-->| dataTypes.dtd
---| ... 其余文件/文件夹,无需检查,可任意存在

现有代码

import os

required_files = [
    'datatypes.dtd'           ,
    'lom.xsd'                 ,
    'xml.xsd'                 ,
    'XMLSchema.dtd'           ,
    'common\\anyElement.xsd'          ,
    'common\dataTypes.xsd'           ,
    'extend\strict.xsd'       ,
    'unique\loose.xsd'        ,
    'unique\strict.xsd'       ,
    'vocab\custom.xsd'        ,
    'vocab\loose.xsd'         ,
    'vocab/strict.xsd'        , # 故意写错,用于测试代码是否能检测到缺失
]

def check_name(x):
        # 该函数在另一个脚本中被调用,用户点击按钮选择路径后存入x
        # 测试时使用桌面文件夹路径

        path = x
        directory = path.replace("/", "\\")

        for d in next(os.walk(directory))[1]:
                itempath = os.path.join(directory, d)
                path = d
                if any(letter.isupper() for letter in path):
                        print(" Root folder contains invalid characters at:\n" + itempath) # 检查项目根文件夹是否包含大写字母

                check_required_files = [] # 生成待检查列表的初始思路

                for i in required_files: # 生成完整路径的待检查文件列表
                        filepath = os.path.join(directory,d, i)
                        print(filepath)
                        check_required_files.append(filepath)

                for root, directories, files in os.walk(directory):

                        for name in directories: 
                                # 检查文件夹是否包含非法字符(大写字母)
                                if any(letter.isupper() for letter in name):
                                        print(f"The Folder '{name}' contains illegal characters at\n" + os.path.join(root, name))
                                        print('dirs ' + root)
                                else:
                                        pass

                        for fname in files:

                                fname = os.path.join(root, fname)
                                if any([i in fname for i in check_required_files]):
                                        print(fname)

问题描述

尝试将预设文件列表与os.walk生成的文件列表对比时,核心问题是部分文件位于子文件夹中,生成的列表未包含路径导致无法定位缺失文件位置。目前通过在预设列表中手动添加路径的方式解决,但方法粗糙。

当前代码中if any([i in fname for i in check_required_files]):的思路无法实现需求:用if not any会输出所有文件,if any([i in fname for i not in check_required_files]):会产生语法错误。想确认当前实现思路是否正确,同时考虑过使用glob但担心多个遍历会让代码繁琐。

修正思路与优化代码

你的核心思路方向没问题,但实现逻辑绕了弯路,以下是更简洁高效的优化方案:

优化点说明

  1. 统一路径分隔符:用os.path.normpath()自动处理不同系统的路径分隔符,避免混用/和\导致的路径错误。
  2. 直接检查文件存在性:不需要遍历所有文件再匹配,直接为每个必填文件构造完整路径,用os.path.exists()检查存在性,一步到位定位缺失文件。
  3. 拆分逻辑模块:将项目根文件夹检查、必填文件检查、子文件夹非法字符检查分开,代码结构更清晰。

优化后的代码

import os

# 统一用相对路径定义必填文件,后续自动处理分隔符
required_files = [
    'datatypes.dtd',
    'lom.xsd',
    'xml.xsd',
    'XMLSchema.dtd',
    'common/anyElement.xsd',
    'common/dataTypes.xsd',
    'extend/strict.xsd',
    'unique/loose.xsd',
    'unique/strict.xsd',
    'vocab/custom.xsd',
    'vocab/loose.xsd',
    'vocab/strict.xsd',  # 故意写错的测试项
]

def check_name(x):
    # 标准化输入路径,自动适配系统分隔符
    base_dir = os.path.normpath(x)
    
    # 遍历主文件夹下的所有项目文件夹
    for project_name in next(os.walk(base_dir))[1]:
        project_path = os.path.join(base_dir, project_name)
        
        # 检查项目根文件夹是否含大写字母
        if any(c.isupper() for c in project_name):
            print(f"Root folder contains invalid characters at:\n{project_path}")
        
        # 逐个检查必填文件是否存在
        for rel_file_path in required_files:
            full_file_path = os.path.normpath(os.path.join(project_path, rel_file_path))
            if not os.path.exists(full_file_path):
                print(f"Required file {rel_file_path} is missing at {full_file_path}")
        
        # 遍历所有子文件夹,检查是否含大写字母
        for root, dirs, _ in os.walk(project_path):
            for dir_name in dirs:
                if any(c.isupper() for c in dir_name):
                    dir_full_path = os.path.join(root, dir_name)
                    print(f"The Folder '{dir_name}' contains illegal characters at\n{dir_full_path}")

内容的提问来源于stack exchange,提问作者Avila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:17:05