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. winform在设置控件enabled=false后,无法更改控件字体颜色的问题

    项目界面设计的时候,发现在设置button的enabled=false后,原本设计的字体颜色跟预设的不一样,查了一些资料后,在网上看到这样一段代码: [System.Runtime.InteropSe ...

  2. Voreen(三) 光线投射参数介绍

    本篇介绍光线投射的第二个个制Pass,光线合成的参数,对应于第一篇总的流程介绍中的Processor SingleVolumeRaycaster.可设置的参数如下: 1,Sampling Rate 采 ...

  3. block中如何避免循环引用

    使用 weak–strong dance 技术 block 可以直接引用 self,但是要非常小心地在 block 中引用 self.因为在 block 引用 self,可能会导致循环引用.如下例所示 ...

  4. [转] LBYL与EAFP两种防御性编程风格

    检查数据可以让程序更健壮,用术语来说就是防御性编程.检查数据的时候,有这样的两种不同的风格.LBYL:Look Before You Leap  EAFP:Easier to Ask Forgiven ...

  5. UML和UP简介(转载)

    UML(统一建模语言,Unified Modeling Language)是用于系统的可视化建模语言.  UP(统一过程,Unified Process)是通用的软件开发过程. 很多人或书籍过大的夸大 ...

  6. 给自己~~微语&&歌单

    如果你很忙,除了你真的很重要以外,更可能的原因是:你很弱,你没有什么更好的事情去做,你生活太差不得不努力来弥补,或者你装作很忙,让自己显得很重要.——史蒂夫-乔布斯 时间并不会因为你的迷茫和迟疑而停留 ...

  7. CSS实现垂直居中的5种方法

    利用 CSS 来实现对象的垂直居中有许多不同的方法,比较难的是选择那个正确的方法.我下面说明一下我看到的好的方法和怎么来创建一个好的居中网站. 使用 CSS 实现垂直居中并不容易.有些方法在一些浏览器 ...

  8. 数论 UVAlive 2889

    这是一道考察回文数的题目,要求你输出第k个回文数.在做题的过程中,可以发现回文数的分布的规律:一位数:9个,二位数:9个,三位数:90个,四位数:90个,五位数:900个,六位数:900个……. #i ...

  9. linux文件系统节点详解

    linux文件系统有两层结构,逻辑结构和物理结构.也就是inode和block. 每个文件都有一个inode, 记录文件属性:权限,时间还有最重要的block号码. block是实际存放文件内容的地方 ...

  10. python 3 学习笔记(一)

    由于之前学过python2,因此今天就想记录下第一天学习python3过程中的遇到的不同和之前没有太掌握的基础知识. python2和python3的语法区别 print语句 在Python2里,pr ...