首页 > 解决方案 > 为什么我的脚本无法解析子目录中的 xml 文件?

问题描述

当我尝试解析子目录中的 xml 文件时,我得到一个FileNotFoundError. 当我将文件放在脚本旁边时,它可以很好地解析它。但为什么?

#!/usr/bin/env python3
import os
import xml.etree.ElementTree as ET

script_path = os.path.dirname(os.path.realpath(__file__))

path_to_file = os.path.join(script_path, '/test', 'file.xml')

# works
tree = ET.parse('file.xml')

# Throws file not found error
tree = ET.parse(path_to_file)

标签: pythonxmlparsingelementtree

解决方案


通过打印 path_to_file 的值来尝试最简单的调试方法。

os.path.join()使用,因此您不必为它构造的路径指定(特定于操作系统的)路径分隔符,这意味着您不需要(不应该)指定它们。

您在零件上过度指定了路径分隔符test- 更改:

path_to_file = os.path.join(script_path, '/test', 'file.xml')

path_to_file = os.path.join(script_path, 'test', 'file.xml')

推荐阅读