简体   繁体   English

Python xml.etree.ElementTree目录访问

[英]Python xml.etree.ElementTree directory acess

import xml.etree.ElementTree as ET

ID="000296166"
tree = ET.parse("\folder" + ID +'.xml')
root = tree.getroot()

What I'm trying to do is access XML files that aren't in the same folder as the .py using the function from xml.etree.elementtree 我想要做的是使用xml.etree.elementtree的函数xml.etree.elementtree.py不在同一文件夹中的XML文件

It keeps giving the error: 它不断给出错误:

IOError: [Errno 22] invalid mode ('rb') or filename: '\x0colder000296166.xml'

I keep getting the feeling that I did something wrong when writing the path...but I can't find any examples online to see how it's supposed to work 我一直觉得自己在编写路径时做错了什么...但是我找不到在线示例来了解它应该如何工作

\\f is interpreted as the page brake and is replaced with hex code 0xC . \\f被解释为页面制动器,并用十六进制代码0xC代替。 You should remove leading backslash from path. 您应该从路径中删除前导反斜杠。

tree = ET.parse("folder" + ID +'.xml')

And if you use backslash inside strings it can be escaped like this \\\\ 如果在字符串中使用反斜杠,则可以像这样\\\\

EDIT 编辑

When you work with paths it is better to use os.path module: 使用路径时,最好使用os.path模块:

 import os 
 ...
 tree = ET.parse(os.path.join('folder', ID + '.xml'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM