1.json/pickle   略。

2.shelve模块

import shelve

# shelve 以key value的形式序列化,value为对象
class Foo(object):
def __init__(self, n):
self.n = n
s = shelve.open("shelve_test")
name = ["alex", "rain", "test"]
s["test"] = name
s["a"] = Foo(1)
s["b"] = Foo(2) # 反序列化,提取对象 print(s.items()) # 提取所有
print(s.get("test")) # 提取单个 s.close()

3.xml的处理

xml文件:country.xml

<?xml version="1.0"?>
<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>

遍历等处理:

import xml.etree.ElementTree as ET

tree = ET.parse("country.xml")
root = tree.getroot()   # data 根节点 '''
一般的节点<tag attrib="value"> text <tag/>
自结束标签<tag attrib="value"/>
''' # 遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag, i.text) # 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)

修改和删除:

import xml.etree.ElementTree as ET

tree = ET.parse("country.xml")
root = tree.getroot() # 修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set("updated", "yes") tree.write("country.xml") # 删除node
for country in root.findall('country'): # 或者root.iter('country')
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) tree.write('country.xml')

生成xml文件:

import xml.etree.ElementTree as ET

new_xml = ET.Element("infolist")
info = ET.SubElement(new_xml, "info", attrib={"enrolled": "yes"})
name = ET.SubElement(info, "name")
name.text = 'akira'
age = ET.SubElement(info, "age", attrib={"checked": "no"})
age.text = ''
sex = ET.SubElement(info, "sex")
sex.text = 'F' info1 = ET.SubElement(new_xml, "info", attrib={"enrolled": "yes"})
name1 = ET.SubElement(info1, "name")
name1.text = 'alen'
age1 = ET.SubElement(info1, "age", attrib={"checked": "no"})
age1.text = ''
sex1 = ET.SubElement(info1, "sex")
sex1.text = 'M' et = ET.ElementTree(new_xml) # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)
# <?xml version='1.0' encoding='utf-8'?>
ET.dump(new_xml) # 打印生成的格

生成的xml内容:

<?xml version='1.0' encoding='utf-8'?>
<infolist>
<info enrolled="yes">
<name>akira</name>
<age checked="no">33</age>
<sex>F</sex>
</info>
<info enrolled="yes">
<name>alen</name>
<age checked="no">22</age>
<sex>M</sex>
</info>
</infolist>

4.YAML

Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation

例如下面的格式

/etc/http/conf/http.conf:
file.managed:
- source: salt://apache/http.conf
- user: root
- group: root
- mode: 644
- template: jinja
- defaults:
custom_var: "default value"
other_var: 123

5.configparser

修改配置文件的,格式:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no

解析:(读取配置文件,并查询条目)

import configparser

conf = configparser.ConfigParser()
conf.read("example.conf")
print(conf.defaults()) # DEFAULT下的条目:
# ["ServerAliveInterval":45,"Compression","yes"...]
print(conf.sections()) # 所有选项除DEFAULT:["bitbucket.org","topsecret.server.com"] print(conf["DEFAULT"]["ForwardX11"]) # DEFAULT选项中的"ForwardX11"的值
print(conf["bitbucket.org"]["User"])
print(conf["topsecret.server.com"]["Port"]) for key in conf["DEFAULT"]: # 遍历DEFAULT条目
print(key, conf["DEFAULT"][key])

写入:

import configparser

conf = configparser.ConfigParser()  # 创建配置文件对象
conf.read("example.conf") # 读取配置文件 conf.write(open("filename.conf", "w")) # 配置文件对象写入文件

用Python生成这个文档:

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)

“增,删,改”:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('i.cfg') # ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options #item_list = config.items('group2')
#print item_list #val = config.get('group1','key')
#val = config.getint('group1','key') # ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w")) #sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w")) #config.set('group2','k1',11111)
#config.write(open('i.cfg', "w")) #config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

6、hashlib

加密相关操作,3.x里代替了md5和sha模块,提供 SHA1 , 224,256,384,512,MD5算法,MD5算法是hash散列表的一种实现,也是应用最广泛的一种

hashlib,hash字符串转数字,字典就是用hash做的,字符串排序,存取速度快,

网站防篡改报警功能,定时wget网站首页,如果文件没有变更,MD5值不变

SHA1----MD5   越来越复杂,越来越安全,都是基于hash的

hmac消息加密速度比较快

中文需要 ("中文".encode(encoding="utf8"))    MD5的加密,其他SHA..一样的用法

import hashlib

#  先加hello, 再加world
m = hashlib.md5()
m.update("hello".encode("utf8"))
print(type("hello".encode("utf8"))) # <class 'bytes'>
m.update("world".encode("utf8"))
print(m.digest()) # MD5 二进制表示b'\xfc^\x03\x8d8\xa5p2\x08TA\xe7\xfep\x10\xb0'
print(m.hexdigest()) # 十六进制表示fc5e038d38a57032085441e7fe7010b0 # 直接helloworld
m1 = hashlib.md5()
m1.update("helloworld".encode("utf8"))
print(m.digest()) # b'\xfc^\x03\x8d8\xa5p2\x08TA\xe7\xfep\x10\xb0'
print(m.hexdigest()) # fc5e038d38a57032085441e7fe7010b0

还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密

散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;

一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。

import hmac
h = hmac.new('天王盖地虎'.encode("utf8"), '宝塔镇河妖'.encode("utf8"))
print (h.hexdigest())

Python学习第二阶段Day2(json/pickle)、 shelve、xml、PyYAML、configparser、hashlib模块的更多相关文章

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

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

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

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

  3. Python全栈开发记录_第八篇(模块收尾工作 json & pickle & shelve & xml)

    由于上一篇篇幅较大,留下的这一点内容就想在这里说一下,顺便有个小练习给大家一起玩玩,首先来学习json 和 pickle. 之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过, ...

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

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

  5. Python day19 模块介绍3(sys,json,pickle,shelve,xml)

    1.sys模块 import sys sys.path()#打印系统path sys.version()#解释程序版本信息 sys.platform()#系统平台 sys.exit(0)#退出程序 c ...

  6. python笔记-7(shutil/json/pickle/shelve/xml/configparser/hashlib模块)

    一.shutil模块--高级的文件.文件夹.压缩包处理模块 1.通过句柄复制内容 shutil.copyfileobj(f1,f2)对文件的复制(通过句柄fdst/fsrc复制文件内容) 源码: Le ...

  7. PYTHON-模块 json pickle shelve xml

    """ pickle 和 shevle 序列化后得到的数据 只有python才能解析 通常企业开发不可能做一个单机程序 都需要联网进行计算机间的交互 我们必须保证这个数据 ...

  8. 常用模块(json/pickle/shelve/XML)

    一.json模块(重点) 一种跨平台的数据格式 也属于序列化的一种方式 介绍模块之前,三个问题: 序列化是什么? 我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化. 反序列化又是什么? 将 ...

  9. json/pickle/shelve/xml/configparser/hashlib/subprocess - 总结

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

随机推荐

  1. 牛了个逼,phpstorm查询技巧

    两次shift,会弹出最近常用的文件. 可以查询按照方法名,类名,文件名等进行查询. Ctrl+E可以查看最近使用的文件. Ctrl+Shift+E可以查看最近修改的文件. Ctrl+shift+N ...

  2. 关于ExecuteNonQuery执行存储过程的返回值 、、实例讲解存储过程的返回值与传出参数、、、C#获取存储过程的 Return返回值和Output输出参数值

    关于ExecuteNonQuery执行存储过程的返回值 用到过ExecuteNonQuery()函数的朋友们在开发的时候肯定这么用过. if(cmd.ExecuteNonQuery("xxx ...

  3. uml图六种箭头的含义(转载)

    在看一些技术博客的时候,经常会见到博客里画上很多uml图.因为经常会被这几种表达关系的箭头搞混,这里我就把常见的6种箭头表达的含义理一下. 泛化 概念:泛化是一种一般与特殊.一般与具体之间关系的描述, ...

  4. bzoj 1734: [Usaco2005 feb]Aggressive cows 愤怒的牛【二分+贪心】

    二分答案,贪心判定 #include<iostream> #include<cstdio> #include<algorithm> using namespace ...

  5. 流程图软件draw.io

    工作中经常需要梳理一些流程图,时序图.以前用微软Visio绘制流程图(当然不是正版Visio).后来为了响应国家号召,改用processon(proceson.com)进行绘制流程图.Processo ...

  6. JAXB解析xml 的注解说明

      1.将 xml 文件中的各个节点和属性信息创建对应的Java模型 2.在Java模型中的创建与 xml 文件对应的节点和属性需要用注解来表示@XmlRootElement   将一个Java类映射 ...

  7. 对路径 obj 文件夹访问被拒绝

    TFS 刚下载的项目,出现该问题. 解决方案: 将文件夹属性“只读”,取消

  8. 思维题+set URAL 1718 Rejudge

    题目传送门 /* 题意:数据加10组,再删掉第6组数据,问rejudge后最少最多几个作者收到邮件 思维题:当错在6时结果是不一定,错在7时是一定改变,因为会变成6 思路没错,但用结构题排序一直WA, ...

  9. putty中文乱码问题解决

    ###putty中文乱码问题解决 用putty从windows xp连接ubuntu server或者FreeBSD系统,其中中文部分乱码,经常遇到这个问题的时候,会觉得很郁闷.现共享一些解决这个问题 ...

  10. FCC 基础JavaScript 练习2

    1. 引号不是字符串中唯一的可以被转义字符.下面是常见的转义序列列表: \'  单引号 \" 双引号 \\ 反斜杠符 \n 换行符 \r 回车符 \t 制表符 \b 退格符 \f  换页符 ...