简体   繁体   English

Python编写XML而不覆盖输入

[英]Python writing to XML and not over writing input

I am attempting to create a program that will allow me to take in peoples info and then write it to an xml doc, save it, and then once the program is ran again, it will pick up from where I left off. 我正在尝试创建一个程序,该程序将允许我输入人的信息,然后将其写入xml文档,保存,然后再次运行该程序,它将从我上次中断的地方开始运行。 All I am getting right now is I am overwriting the same line over and over. 我现在得到的只是一遍又一遍地覆盖同一行。 It shows 表明

<person>
     <name>Users Name</name>
</person>

and that is it. 就是这样。 I need it to do 我需要做

<person>
     <name>User 1</name>
</person>

<person>
     <name>User 2</name>
</person>

So on and so on... I am still working on the code, but there is not sense in working on the code if I cannot write to it. 依此类推……我仍在编写代码,但是如果我无法编写代码,那么在编写代码时就没有意义。 I have tried open('person.xml','(w,r,a') and still nothing. My code is 我已经尝试过open('person.xml','(w,r,a'),仍然没有。我的代码是 我的密码

You need to append to the file just using a not overwrite: 您只需要使用a不可覆盖的内容附加到文件:

with open("your.xml", "a") as f:
    tree.write(f)

w truncates your file data so basically you are emptying your file before you write hence you only see one entry, . w截断文件数据,因此基本上可以在写之前清空文件,因此只能看到一个条目。

Your file should be opened in append mode when you want to write something to it so that existing content doesn't get replaced. 当您要向文件写入内容时,应以append mode打开文件,以免替换现有内容。
You should change this line of code: 您应该更改以下代码行:

tree.write(open('person.xml', 'w'))

with this one (notice a instead of w ): 与此(注意a而不是w ):

tree.write(open('person.xml', 'a'))

r : open file in read mode r :以读取模式打开文件
w : open file in write mode w :以模式打开文件
a : open file in append mode a :以追加模式打开文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM