brewersfan1976

ch6-ex3.py

Aug 12th, 2015
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. # this program takes the XML code that we created in exercise 2
  2. # and converts it back to JSON and stores it in a file.
  3.  
  4. # import the xml converter and the json library
  5.  
  6. import xmltodict, json
  7.  
  8. # open the XML.txt file
  9.  
  10. file = open("XML.txt", "r")
  11.  
  12. # open the JSON.txt file to write to
  13.  
  14. file_output = open("JSON.txt", "w")
  15.  
  16. # load the XML data into a variable
  17.  
  18. data = file.read()
  19.  
  20. # create a dictionary
  21.  
  22. d = {}
  23.  
  24. # take the XML variable data and convert it to a python dictionary
  25.  
  26. d = xmltodict.parse(data)
  27.  
  28. # take the dictionary and convert it to JSON format
  29.  
  30. json_format = json.dumps(d)
  31.  
  32. # write the json data to a text file
  33.  
  34. file_output.write(json_format)
  35.  
  36. # we are all done now it is time to close both files
  37.  
  38. file.close()
  39. file_output.close()
Advertisement
Add Comment
Please, Sign In to add comment