Python 如何强制ElementTree每次更改都写入磁盘?

Python 如何强制ElementTree每次更改都写入磁盘?,python,elementtree,Python,Elementtree,我必须处理从一个大数据库创建的一个巨大的XML文件 我从数据库结构生成了一个XML树,但它最终占用了我所有的内存(现在超过10gb),因此该过程永远不会结束,因为系统无法处理任何新查询 我认为解决方案是避免将所有XML结构保存到内存中,并在添加新内容时将其直接转储到磁盘中 这是我真正能做的吗?怎么做 谢谢 我不确定你的代码到底是如何工作的,但这肯定是可以做到的。根据它的结构,您可以创建一个时间戳并将传入数据与旧数据进行比较,或者扫描该文件以确定是否已经添加了当前XML。在此之后(假设其新代码),

我必须处理从一个大数据库创建的一个巨大的XML文件

我从数据库结构生成了一个XML树,但它最终占用了我所有的内存(现在超过10gb),因此该过程永远不会结束,因为系统无法处理任何新查询

我认为解决方案是避免将所有XML结构保存到内存中,并在添加新内容时将其直接转储到磁盘中

这是我真正能做的吗?怎么做


谢谢

我不确定你的代码到底是如何工作的,但这肯定是可以做到的。根据它的结构,您可以创建一个时间戳并将传入数据与旧数据进行比较,或者扫描该文件以确定是否已经添加了当前XML。在此之后(假设其新代码),您可以执行以下操作:

path = "path/"
name = "fileName"

xmlRoot = Element("root")#create a root element for the xml structure
xmlSub = SubElement(xmlRoot,"sub")
subName = SubElement(xmlCard,"name")
subName.text = "element text"

saveName = path + name + ".xml" #constructs location of xml file (path/fileName.xml)
tree = ElementTree(xmlRoot) #compiles the tree
tree.append(saveName) #appends to specified file
xml = parse("path/fileName.xml")
nameList = xml.findall("sub/name") #find all objects in <name> brackets
for i in nameList:
    i.text #convert item in the list to a readable string
    #do comparison here
这将在名为“fileName.xml”的文件夹“path”中的文档中输出以下内容


元素文本
如果要扫描XML文档中的对象,请执行以下操作:

path = "path/"
name = "fileName"

xmlRoot = Element("root")#create a root element for the xml structure
xmlSub = SubElement(xmlRoot,"sub")
subName = SubElement(xmlCard,"name")
subName.text = "element text"

saveName = path + name + ".xml" #constructs location of xml file (path/fileName.xml)
tree = ElementTree(xmlRoot) #compiles the tree
tree.append(saveName) #appends to specified file
xml = parse("path/fileName.xml")
nameList = xml.findall("sub/name") #find all objects in <name> brackets
for i in nameList:
    i.text #convert item in the list to a readable string
    #do comparison here
xml=parse(“path/fileName.xml”)
nameList=xml.findall(“sub/name”)#查找括号中的所有对象
对于姓名列表中的i:
i、 text#将列表中的项转换为可读字符串
#在这里做比较

我希望这有帮助!快乐编码

谢谢!我最终选择了另一个解决方案(根本没有xml!),但您的答案很好。很高兴听到您找到了答案!与eTree一起工作有时可能会很烦人。快乐编码!