json

.dumps()    变成 json 的字符串

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

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

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

把字典写进去  并读出来

 import json
dic={"name":"alex"}
data=json.dumps(dic)
with open("hello",'w')as f:
f.write(data)
with open("hello","r")as f_read:
data=json.loads(f_read.read())
print(data)
print(type(data))
>>>{'name': 'alex'}
>>><class 'dict'>

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

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

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

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

边写边读

 import json
dic={"name":"alex"}
with open("hello","w")as f:
json.dump(dic,f)
with open("hello","r")as f:
print(json.load(f)["name"])
>>>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)

.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 = ''#赋一个属性 name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '' 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)

json&pickle&xml的更多相关文章

  1. json pickle xml shelve configparser

    json:# 是一种跨平台的数据格式 也属于序列化的一种方式pickle和shevle 序列化后得到的数据 只有python才可以解析通常企业开发不可能做一个单机程序 都需要联网进行计算机间的交互 J ...

  2. Python学习第十二课——json&pickle&XML模块&OS模块

    json模块 import json dic={'name':'hanhan'} i=8 s='hello' l=[11,22] data=json.dumps(dic) #json.dumps() ...

  3. Python学习笔记——基础篇【第六周】——json & pickle & shelve & xml处理模块

    json & pickle 模块(序列化) json和pickle都是序列化内存数据到文件 json和pickle的区别是: json是所有语言通用的,但是只能序列化最基本的数据类型(字符串. ...

  4. python 序列化及其相关模块(json,pickle,shelve,xml)详解

    什么是序列化对象? 我们把对象(变量)从内存中编程可存储或传输的过程称之为序列化,在python中称为pickle,其他语言称之为serialization ,marshalling ,flatter ...

  5. python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

    python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess ...

  6. 模块 - json/pickle/shelve/xml/configparser

    序列化: 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化: 有种办法可以直接把内存数据(eg:10个列表,3 ...

  7. 【python】-- json & pickle、xml、requests、hashlib、shelve、shutil、configparser、subprocess

    json & pickle Python中用于序列化的两个模块 json     用于[字符串]和 [python基本数据类型] 间进行转换 pickle   用于[python特有的类型] ...

  8. Python模块:shutil、序列化(json&pickle&shelve)、xml

    shutil模块: 高级的 文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fscr,fdst [, length])   # 将文件内容拷贝到另一个文件中 import shu ...

  9. Python学习第二阶段Day2(json/pickle)、 shelve、xml、PyYAML、configparser、hashlib模块

    1.json/pickle   略. 2.shelve模块 import shelve # shelve 以key value的形式序列化,value为对象 class Foo(object): de ...

随机推荐

  1. Html 之div+css布局之css基础

    Css是什么 CSS即层叠样式表(Cascading StyleSheet). 在网页制作时采用层叠样式表技术,可以有效地对页面的布局.字体.颜色.背景和其它效果实现更加精确的控制. 只要对相应的代码 ...

  2. 对上次“对字符串进行简单的字符数字统计 探索java中的List功能 ”程序,面向对象的改进

    之前的随笔中的程序在思考后发现,运用了太多的static 函数,没有将面向对象的思想融入,于是做出了一下修改: import java.util.ArrayList; import java.util ...

  3. js - 奇怪的回调探索

    做一个手机端页面是发现的奇怪的问题,函数调用的问题(回调). 一句话描述: 某一个dom元素绑定的事件函数在全局能trigger方法调用,但是在ajax成功回调函数里不能被trigger方法调用. 具 ...

  4. 医院管理者必须知道的医院客户关系管理(CRM)

    客户关系管理(customer relationship management,CRM)是在二战之后首先由美国IBM.道氏.通用等大型企业提出并运用的一种以有效销售为目的的市场营销思想,其理论基础就是 ...

  5. App Transport Security has blocked a cleartext HTTP (http://)

    使用SDWebImage加载“http://”开头的图片报错,错误如下: App Transport Security has blocked a cleartext HTTP (http://) r ...

  6. pyqt4:连接的一个带有参数的方法

    一般在pyqt4中的信号连接很少连接带参数的方法,很多时候连接带参数的方法节约不少代码量. self.s5_thread=scene.Worker5() self.log_get=QtCore.QTi ...

  7. Quartus II 增量编译

    在开发阶段,经常需要改代码,而且往往只改局部代码,但是编译的时候,通常会全部重新编译,这会很浪费时间,使得开发效率大大降低.那么有没有一种方法能够降低不必要的编译时间呢?通过查询Quartus II ...

  8. [原创]cocos2d-x研习录-第三阶 特性之物理引擎

    游戏物理引擎是指在游戏中涉及物理现象的逻辑处理,它用于模拟现实世界的各种物理规律(如赛车碰撞.子弹飞行.物体掉落等),让玩家能够在游戏中有真实的体验. Cocos2D-x中支持Box2D和Chipmu ...

  9. zend studio 配置 apache服务器事宜

    安装好 zend studio后,配置 apache服务器时,设置 configuration directory时,需选中 xampp\apache里面的 conf 文件夹,即完整的路径为: *\x ...

  10. PostgreSQL的权限查询

    查看哪些用户对表sns_log_member_b_aciton有哪些权限: sns_log=> \z sns_log_member_b_aciton Access privileges Sche ...