Python xml.etree.ElementTree directory acess

旧巷老猫 提交于 2020-01-06 11:25:14

问题


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

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


回答1:


\f is interpreted as the page brake and is replaced with hex code 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:

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


来源:https://stackoverflow.com/questions/19351127/python-xml-etree-elementtree-directory-acess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!