试图从我的电脑读取XML文件

时间:2015-06-26 21:01:47

标签: python xml xml-parsing

我正在尝试解析XML,或者更好我试图测试我是否可以访问我的XML文件。但是我在这里得到了这个错误:

 >>>> DomTree = xml.dom.minidom.parse("usc01")
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
DomTree = xml.dom.minidom.parse("usc01")
File "C:\Python34\lib\xml\dom\minidom.py", line 1960, in parse
return expatbuilder.parse(file)
File "C:\Python34\lib\xml\dom\expatbuilder.py", line 910, in parse
with open(file, 'rb') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'usc01'

这是直接来自Python Shell,我试图将usc01.xml移动到python34文件夹,但仍然给我这个错误。

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

尝试使用绝对路径名,或更改为文件所在的目录。例如。任

>>> DomTree = xml.dom.minidom.parse("c:\\Users\\somebody\\Desktop\\usc01.xml")

>>> import os
>>> os.chdir("c:\\Users\\somebody\\Desktop")
>>> DomTree = xml.dom.minidom.parse("usc01.xml")

当然,如果文件确实包含.xml扩展名,则包括parse扩展名。微软认为普通用户的大脑无法同时处理文件名和扩展名,但对于文件系统来说,事情比这更复杂......: - )

更新:以下评论中的错误与文件的内容有关,而这些内容可能是无效的unicode。如果不知道文件在2-3位中包含的内容,很难说明发生了什么。

如果文件的内容采用默认以外的某种编码并且需要翻译,则应首先正确打开文件,然后将文件对象传递给>>> f = open("c:\\Users\\somebody\\Desktop\\usc01.xml", encoding="iso-8859-1") >>> DomTree = xml.dom.minidom.parse(f) 方法,例如:

{
    "_id" : "243kAaNRsEvhrguNs",
    "createdAt" : ISODate("2015-04-07T16:43:15.299Z"),
    "profile" : {
        "balance" : 9.71,
        "deposited" : 0,
        "withdrawn" : 30,
        "virgin" : false,
        "won" : 29.709999999999997,
        "taxable" : false
    }
}