1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# XML -------------------------------------------------------- import xml.etree.ElementTree as et # 作成 root = et.Element("root") tree = et.ElementTree(element=root) user = et.SubElement(root, "user") id = et.SubElement(user, "id") id.text = "1" name = et.SubElement(user, "name") name.text = "taro" # 書き込み tree.write("t.xml", encoding="utf-8", xml_declaration=True) # 読み込み tree = et.ElementTree(file="t.xml") root = tree.getroot() for user in root: for i in user: print(i.tag, i.text) # Json -------------------------------------------------------- import json # 作成 j = { "user": [ {"id":"1", "name":"taro"} ] } # dumps(), dump()でJsonの形にする # ファイルの書き込み読み込みはdump(),load() # 変数の書き込み・読み込みはdumps(), loads() # 書き込み with open("t.json", "w") as f: json.dump(j, f) # 読み込み with open("t.json", "r") as f: print(json.load(f)) # 書き込み tmp = json.dumps(j) # 読み込み print(json.loads(tmp)) |