python基础学习(四)

来源:互联网 发布:淘宝发布宝贝被限制 编辑:程序博客网 时间:2024/06/01 08:45

python序列化之json

import jsondic={'name':'one','age':'18'}json.dumps(dic)# 类型变成了json字符串类型print(type(json.dumps(dic)))# 要是想永久保存,就写到文件中# 第一种# 写with open('a.json','w') as f:    f.write(json.dumps(dic))# 读with open('a.json','r') as f:    data=f.read()# 转化为字典类型    dic=json.loads(data)    print(dic['name'])# 第二种dic={'name':'one','age':'18'}# 写json.dump(dic,open('b.json','w'))# 读json.load(open('b.json','r'))print(json.load(open('b.json','r'))['name'])

eval和json的区别:

eval是将字符串中的命令提取出来,执行一遍

json是把一个数据类型按照json类型转成json认识的字符串,即json序列化。json反序列化就是将json类型转化为原来的类型

 

shelve存取数据

import shelve# 存数据f=shelve.open(r'shelve.sh')f['one']={'age':18,'pwd':'123'}f['two']={'age':28,'pwd':'456'}# 别忘了close掉f.close()

import shelve# 取数据f=shelve.open(r'shelve.sh')res=f['one']f.close()print(res)

xml模块:

import xml.etree.ElementTree as ETtree=ET.parse('a.xml')root=tree.getroot()for child in root:    print('===>',child)    for i in child:        # 打印标签,属性,内容        print(i.tag,i.attrib,i.text)

查找element元素的三种方式:

import xml.etree.ElementTree as ETtree=ET.parse('a.xml')root=tree.getroot()# 查找element元素的三种方式# 第一种:years=root.iter('year')#扫描整个xml文档树for i in years:    print(i)# 第二种:res1=root.find('country')#谁来调,就从谁的下一层中找第一个print(res1)# 第三种:res2=root.findall('country')#谁来调,就从谁的下一层中找所有print(res2)
























原创粉丝点击