没有这样的文件或目录:'<root> \ n </root>

时间:2012-11-20 21:30:10

标签: python

每当有xml(productline)函数调用时,我都会收到以下错误,但如果我用file = open('config\\' + productLine + '.xml','r')替换函数调用,它似乎有效,为什么?

def xml(productLine):
         with open('config\\' + productLine + '.xml','r') as f:
    return f.read()


def getsanityresults(productline):

xmlfile=xml(productline) // replace with file = open('config\\' + productLine + '.xml','r')
dom = minidom.parse(xmlfile)
data=dom.getElementsByTagName('Sanity_Results')
#print "DATA"
#print data
textnode = data[0].childNodes[0]
testresults=textnode.data
#print testresults
for line in testresults.splitlines():
    #print line
    line = line.strip('\r,\n')
    #print line
    line = re.sub(r'(http://[^\s]+|//[^\s]+|\\\\[^\s]+)', r'<a href="\1">\1</a>', line)
    print line
    #print line       
    resultslis.append(line)
print resultslis
return resultslis

错误:

Traceback (most recent call last):
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 910, in <module>
  main()
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 858, in main
testresults=getsanityresults(pL)
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 733, in   getsanityresults
  dom = minidom.parse(xmlfile)
File "C:\python2.7.3\lib\xml\dom\minidom.py", line 1920, in parse
   return expatbuilder.parse(file)
File "C:\python2.7.3\lib\xml\dom\expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 2] No such file or directory: '<root>\n    <PL name = "MSM8930.LA.2.0-PMIC-8917">\n

2 个答案:

答案 0 :(得分:1)

  

我将功能调用替换为file = open('config\\' + productLine + '.xml','r'),它似乎有用,为什么?

你有两个变量,名字略有不同:

xmlfile=xml(productline) // replace with file = open('config\\' + productLine + '.xml','r')

productline(小写l)和productLine(大写L)。

如果在两种情况下使用相同的变量,您可能会看到更一致的结果。

答案 1 :(得分:1)

minidom.parse()要求文件名或文件对象作为参数,但是你要传递文件的内容,试试这个:

import os
from xml.dom import minidom

doc = minidom.parse(os.path.join('config', productline + '.xml'))

除非您有特定要求,否则minidom;使用xml.etree.cElementTree在Python中使用xml。在更复杂的情况下,您可能需要更加pythonic和lxml支持其API,因此您无需学习两次。

相关问题