0

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 My Code

0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Thank you so much! I saw this elsewhere and I couldn't figure it out, but I managed to figure it out with you code. Thank you so much! You have saved me days of head pounding!
0

This worked for me:

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

I had to write 'ab' instead of 'a', and added b for binary mode.
reference: https://stackoverflow.com/a/5513856/3182598

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.