简体   繁体   中英

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. 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 我的密码

You need to append to the file just using a not overwrite:

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, .

Your file should be opened in append mode when you want to write something to it so that existing content doesn't get replaced.
You should change this line of code:

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

with this one (notice a instead of w ):

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

r : open file in read mode
w : open file in write mode
a : open file in append mode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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