python - 为什么我的脚本无法解析子目录中的 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)
解决方案
通过打印 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')
推荐阅读
- c - 即使在手动释放内存后,valgrind 也会显示内存泄漏
- python - 使用 pyyaml 序列化自定义类
- ios - Camera.app 使用什么 AVCaptureDevice?
- weka - Weka 异常:训练和测试文件不兼容!尽管有可以纠正这种不兼容性的过滤器,但还是抛出了
- python - pandas-groupby 中一行的出现顺序
- java - 禁用在弹簧启动中将正斜杠替换为一个斜杠
- java - 递归遍历二叉搜索树前序
- sql - SQLite 子查询可以包含 ORDER BY 吗?
- ansible - 在配置期间在每台 Vagrant 机器上运行的 Ansible 提供程序
- python - Moto 不模拟 DynamoDB