zoukankan      html  css  js  c++  java
  • json&pickle&xml

    json

    .dumps()    变成 json 的字符串

    1 import json
    2 dic={"name":"alex"}
    3 data=json.dumps(dic)
    4 print(type(data))
    5 >>><class 'str'>

    .loads()   把字符串变成源类型

    1 with open("hello","r")as f_read:
    2     data=json.loads(f_read.read())
    3     print(data)
    4     print(type(data))
    5 >>>{'name': 'alex'}
    6 >>><class 'dict'>

    把字典写进去  并读出来

    1 import json
    2 dic={"name":"alex"}
    3 data=json.dumps(dic)
    4 with open("hello",'w')as f:
    5     f.write(data)
    6 with open("hello","r")as f_read:
    7     data=json.loads(f_read.read())
    8     print(data)
    9     print(type(data))
    >>>{'name': 'alex'}
    >>><class 'dict'>

    .dump()   直接转成字符串  并  放到文件里

    1 import json
    2 dic={"name":"alex"}
    3 with open("hello","w")as f:
    4     json.dump(dic,f)

    .load()    转成原类型并读出来

    with open("hello","r")as f:
        data=json.load(f)
      print(data)

    边写边读

    1 import json
    2 dic={"name":"alex"}
    3 with open("hello","w")as f:
    4     json.dump(dic,f)
    5 with open("hello","r")as f:
    6     print(json.load(f)["name"])
    7 >>>alex

    转换时间

    import json
    from datetime import datetime
    from datetime import date
     
    class JsonCustomEncoder(json.JSONEncoder):
        def default(self, field):
            if isinstance(field,datetime):
                return field.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(field,date):
                return field.strftime('%Y-%m-%d')
            else:
                return json.JSONEncoder.default(self,field)  # 使用默认的
     
    data = {
        "k1":123,
        "k2":datetime.now()
    }
     
    ds = json.dumps(data,cls=JsonCustomEncoder)
    print(ds)

    pickle

    跟json差不多   但是要以字节的方式读取  自己看不到

    import pickle
    dic={"name":"alex"}
    with open("hello","wb")as f:
        f.write(pickle.dumps(dic))
    with open("hello","rb")as f:
        print(pickle.loads(f.read())["name"])
    >>>alex

     xml

    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    xml文件

     

    .tag  打印标签的名字   parse解析文件得到一个对象  getroot获取根对象

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,根对象赋值给root    ,root是一个对象
    print(root.tag) #tag是取标签的名字,在根对象下用就是取根节点的标签名     

    .getroot的结果是对象可以被便利

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    print(root.tag) #tag是取标签的名字,在根对象下用就是取根节点的标签名
    for i in root:  # i 是根对象下的子对象
        print(i,i.tag)  # i.tag 是根节点下的子节点的标签名
    tag打印标签名

    还可以继续便利

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    print(root.tag) #tag是取标签的名字,在根对象下用就是取根节点的标签名
    for i in root:  # 便利根节点,i 是根对象下的子对象
        # print(i,i.tag)  # i.tag 是根节点下的子节点的标签名
        for j in i: #便利根下面的子节点,j 是子节点下的子节点
            print(j.tag)    #获取便利根下面的子节点下面标签名
    tag打印标签名

    .attrib  打印 标签的属性

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for i in root:  # 便利根节点,i 是根对象下的子对象
        print(i.attrib) #打印标签的属性
    .attrib打印标签的属性
    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for i in root:  # 便利根节点,i 是根对象下的子对象
        # print(i.attrib) #打印标签的属性
        for j in i: #便利根下面的子节点,j 是子节点下的子节点
            print(j.attrib)
    View Code

    .text   把标签所有文本内容全都取出来

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for i in root:  # 便利根节点,i 是根对象下的子对象
        # print(i.attrib) #打印标签的属性
        for j in i: #便利根下面的子节点,j 是子节点下的子节点
            # print(j.attrib)
            print(j.text)
    .text取内容

    便利xml

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for child in root:
        print(child.tag,child.attrib)
        for i in child:
            print(i.tag,i.text)
    便利xml并取值

    取一个标签    便利属性  从外往里找

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for node in root.iter("year"):  #获取year标签
        print(node.tag,node.text)   #取year的标签名和内容
    .iter取year标签

    修改属性  写入文件 ,一个覆盖的功能

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for node in root.iter("year"):
        #修改内容
        new_year=int(node.text)+1
        node.text=str(new_year)
        #修改属性
        node.set("updated","yes")
        #写进一个新的文件
        tree.write("abc.xml")
    修改属性

    删除  

    用.findall()找到country标签

    再用.find()找到randk标签

    import xml.etree.ElementTree as ET  #导入模块,ET是一个简写的名字
    tree=ET.parse("xml_lesson") #parse是解析的意思,拿到一个对象赋值给tree,
    root=tree.getroot() #对象下面的getroot方法,叫文档树,把根对象赋值给root
    for country in root.findall("country"):#找到country之后进行便利
        rank=int(country.find("rank").text)#找到rank之后取值,转数字后从新赋值
        if rank>50:#判断结果大于50
            root.remove(country)#删除整个country
    tree.write("output.xml")#从新写文件
    删除country

    创建xml

    import xml.etree.ElementTree as ET
    
    <namelist>
        <name enrolled="yes"></name>
            <age checked="no"></age>
            <sex>33</sex>
    </namelist>
    
    new_xml = ET.Element("namelist")#创建一个根节点
    name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})#创建标签和属性
    age = ET.SubElement(name, "age", attrib={"checked": "no"})
    sex = ET.SubElement(name, "sex")
    sex.text = '33'#赋一个属性
    
    name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
    age = ET.SubElement(name2, "age")
    age.text = '19'
    
    et = ET.ElementTree(new_xml)  # 生成文档对象,生成文档树
    et.write("test.xml", encoding="utf-8", xml_declaration=True)#写到一个文件里
    
    ET.dump(new_xml)  # 打印生成的格式

    背下来

    et=ET.ELementTree(new_xml)  #生成文档对象
    et.write("test.xml",encoding="utf-8",xml_declaration=True)
  • 相关阅读:
    每日一道 LeetCode (11):外观数列
    每日一道 LeetCode (10):搜索插入位置
    每日一道 LeetCode (9):实现 strStr()
    每日一道 LeetCode (8):删除排序数组中的重复项和移除元素
    每日一道 LeetCode (7):合并两个有序链表
    每日一道 LeetCode (6):有效的括号
    Python 图像处理 OpenCV (16):图像直方图
    每日一道 LeetCode (5):最长公共前缀
    每日一道 LeetCode (4):罗马数字转整数
    每日一道 LeetCode (3):回文数
  • 原文地址:https://www.cnblogs.com/shizhengwen/p/6182542.html
Copyright © 2011-2022 走看看