lxml文件打开方法

时间:2016-02-02 14:39:32

标签: python lxml

我一直习惯写作:

with open('path/my_document.xml', 'rb') as xml_document:
    return etree.parse(xml_document)

我最近才意识到我可以写

return etree.parse('path/my_document.xml')

假设我不需要将xml_document变量用于其他任何事情,是否存在真实情况,两者之间存在差异?

etree.parse的源代码:

def parse(self, source, _BaseParser parser=None, *, base_url=None):
    u"""parse(self, source, parser=None, base_url=None)
    Updates self with the content of source and returns its root
    """
    cdef _Document doc = None
    try:
        doc = _parseDocument(source, parser, base_url)
        self._context_node = doc.getroot()
        if self._context_node is None:
            self._doc = doc
    except _TargetParserResult as result_container:
        # raises a TypeError if we don't get an _Element
        self._context_node = result_container.result
    return self._context_node

0 个答案:

没有答案