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. 关于Windows7的安装纠结过程

    关于Windows7的安装过程 背景交代 因为自己有两个笔记本,一个是伴我读过四年大学生活的老华硕笔记本,一个是姐夫不用的上网本.自己的构想是将老笔记本装上Ubuntu Server当作平时开发pyt ...

  2. 问题:C++形参默认值为什么一定要放在最后?

    问题:C++形参默认值为什么一定要放在最后? 1.会出现歧义! 2.从汇编角度看是怎么回事?   待解答!!

  3. 托管到github上的网页图片在百度浏览器中显示不全

    这几天做了个较完整的网页放到github上,上传后看网页效果. 在Firefox浏览器中,显示正常. 在百度浏览器中,空了一大块位置(图片位置),偏偏只空了这一块,其它地方的图片都好好的. 点击f12 ...

  4. linux sed和awk的区别

    awkawk是一种程序语言,对文档资料的处理具有很强的功能.awk擅长从格式化报文或从一个大的文本文件中抽取数据.awk的命令格式为:awk [-F filed-separator] “command ...

  5. python向数据库插入数据时出现乱码解决方案

    中文字符串前面加u 如: title =u"你好" contents = "m" ids="13" cur.execute("IN ...

  6. 通过gradle来导入jar包

    1.通过gradle配置第三方jar包 我们看到,每个module都有一个build.gradle文件,它其实是对应module的配置文件.关于build.gradle文件中具体内容的含义,我们将在最 ...

  7. CGRectInset & CGRectOffset

    1.CGRectInset CGRect CGRectInset (   CGRect rect,   CGFloat dx,   CGFloat dy);以原rect为中心,再参考dx,dy,进行缩 ...

  8. Shiro中的subject.login()

    当调用ShiroHandler中的subject.login()的时候,会自动调用Realm中的doGetAuthenticationInfo方法.

  9. pwnable echo2

    pwnable echo2 linux 32位程序 涉及FSB和UAF漏洞的利用,先%x泄露地址,然后利用UAF漏洞进行利用 code:

  10. webstorm 10 出现不能run cordova项目

    could not create the java virtual machine Error occurred during initialization of VM Could not reser ...