0

I wrote a code that must modify some values in a xml file. it looks to be working, but when i open this xml file threw PyCharm where i have added the modified file, it just doesn't change a thing. If anyone gave a respond to such a question, please point me where is it. Here is the code as well as the xml.

import xml.etree.ElementTree as ET
tree = ET.parse("farms.xml")
root = tree.getroot()
for elem in root.findall('farm'):
    elem.set('money', '2000')
    money = elem.get('money')
    print(money)

xml

<farms>
  <farm farmId="1" name="Моя ферма" color="1" loan="0.000000" money="213" loanAnnualInterestRate="304.166656">
  <players>
  </players>       
 </farm>
</farms>
3
  • You don’t appear to have included any code that’s writing changes back to the file in the file system - can you elaborate on how you came to the conclusion that the code provided here should function otherwise? Commented Nov 19, 2020 at 13:20
  • i thought that the set function would change in the elem the string with money to 2000. IDK why the ` isnt working Commented Nov 19, 2020 at 13:23
  • it is my first experience working with xml, could you tell me how should i do it otherwise? Commented Nov 19, 2020 at 13:25

2 Answers 2

1

What you are missing is writing the tree back to disk.

import xml.etree.ElementTree as ET

tree = ET.parse("farms.xml")
root = tree.getroot()
for elem in root.findall('farm'):
    elem.set('money', '2000')
with open('new_farms.xml', 'wb') as f:
    tree.write(f)
Sign up to request clarification or add additional context in comments.

3 Comments

it does work, but the problem is i do not need to create a new file, can you help me replace the information in this one?
sure. just change open('new_farms.xml', 'wb') to open('farms.xml', 'wb')
@JustStarted Glad I managed to help. Feel free to up vote.
0

It works for me. Additionally,

print(xml.etree.ElementTree.tostring(root))

will show what you expect.

3 Comments

where shoul i add it. here is the V2 of the code.import xml.etree.ElementTree as ET def main(char): tree = ET.parse("farms.xml") root = tree.getroot() for elem in root.findall('farm'): elem.set('money', '2000') money = elem.get(str(char)) print(xml.etree.ElementTree.tostring(root)) if __name__ == "__main__": char = eval(input("ammount to be set ")) main(char)
oh, i am sorry for that, hopefully you will get the idea
it still doesn t work for me, what does it change for you and what is the setup you are working in

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.