Python指定路径搜索XML文件并排除文件夹的问题排查
问题:读取XML文件时触发PermissionError
问题背景
需要在指定路径下搜索XML文件,路径下包含XML文件以及supplement和serialno两个文件夹,目标是仅处理XML文件并排除这两个文件夹。原代码如下:
path = 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell' for filename in os.listdir(path): if '.' not in filename: if 'MASTER' not in filename: if 'GHOST' and 'serialno' and 'supplement' not in filename: fullname = os.path.join(path, filename) PN, GH, GH_Design_standard = get_data_from_xml(fullname) PN_list.append(PN)
运行时触发以下错误:
--------------------------------------------------------------------------- PermissionError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_14576/1956305515.py in <module> 109 if 'GHOST' and 'serialno' and 'supplement' not in filename: 110 fullname = os.path.join(path, filename) --> 111 PN, GH, GH_Design_standard = get_data_from_xml(fullname) 112 113 PN_list.append(PN) ~\AppData\Local\Temp/ipykernel_14576/1709054135.py in get_data_from_xml(path) 21 22 --> 23 tree = ET.parse(path) 24 #tree = etree.XML(path) 25 root = tree.getroot() C:\Program Files\Anaconda3\lib\xml\etree\ElementTree.py in parse(source, parser) 1227 """ 1228 tree = ElementTree() --> 1229 tree.parse(source, parser) 1230 return tree 1231 C:\Program Files\Anaconda3\lib\xml\etree\ElementTree.py in parse(self, source, parser) 567 close_source = False 568 if not hasattr(source, "read"): --> 569 source = open(source, "rb") 570 close_source = True 571 try: PermissionError: [Errno 13] Permission denied: 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell\\serialno'
错误原因
- 逻辑判断错误:原代码中
'GHOST' and 'serialno' and 'supplement' not in filename的写法不符合Python语法逻辑,实际只会判断'supplement' not in filename,前两个非空字符串会被视为True,导致serialno文件夹未被排除。 - 未校验文件类型:代码未检查当前路径是否为文件,直接尝试读取文件夹路径,触发权限错误(无法以读取文件的方式打开文件夹)。
- 筛选条件颠倒:
if '.' not in filename会排除所有带后缀的文件(包括XML文件),与需求完全相反。
修复方案
直接筛选路径下的XML文件,同时排除指定文件夹,代码如下:
import os import xml.etree.ElementTree as ET path = 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell' PN_list = [] def get_data_from_xml(file_path): tree = ET.parse(file_path) root = tree.getroot() # 补充你的XML解析逻辑,返回PN, GH, GH_Design_standard return "", "", "" for filename in os.listdir(path): fullname = os.path.join(path, filename) # 跳过指定文件夹 if filename in ['serialno', 'supplement']: continue # 仅处理XML文件 if os.path.isfile(fullname) and filename.lower().endswith('.xml'): # 排除包含MASTER或GHOST的文件(按需保留) if 'MASTER' not in filename and 'GHOST' not in filename: PN, GH, GH_Design_standard = get_data_from_xml(fullname) PN_list.append(PN)
关键优化点
- 优先跳过指定文件夹,避免无效处理
- 使用
os.path.isfile()确保处理对象是文件而非文件夹 - 通过
filename.lower().endswith('.xml')精准筛选XML文件(兼容大小写后缀) - 明确判断排除包含
MASTER和GHOST的文件,逻辑清晰易懂
内容的提问来源于stack exchange,提问作者ASAS
相关产品推荐
相关产品推荐

