python 之 random 模块、 shutil 模块、shelve模块、 xml模块
6.12 random 模块
print(random.random()) | (0,1)----float | 大于0且小于1之间的小数 |
---|---|---|
print(random.randint(1,3)) | [1,3] | 大于等于1且小于等于3之间的整数 |
print(random.randrange(1,3)) | [1,3) | 大于等于1且小于3之间的整数 |
print(random.choice ( [1,'23', [4,5] ] ) ) | 1或者23或者[4,5] | |
print(random.sample( [1,'23', [ 4,5 ] ] , 2 ) ) | 第二个参数是任意几个元素组合 | 列表元素任意2个组合 |
print(random.uniform(1,3)) | (1,3) | 大于1小于3的小数,如1.927109612082716 |
import random
item=[1,3,5,7,9]
random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
print(item)
6.121 生成随机验证码
import random
def make_code(n=5):
res=''
for i in range(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])
return res
print(make_code(10))
6.13 shutil 模块
import shutil
import time
ret = shutil.make_archive( # 压缩
"day15_bak_%s" %time.strftime('%Y-%m-%d'),
'gztar',
root_dir=r'D:\code\SH_fullstack_s1\day15'
)
import tarfile # 解压
t=tarfile.open('day15_bak_2018-04-08.tar.gz','r')
t.extractall(r'D:\code\SH_fullstack_s1\day16\解包目录')
t.close()
6.14 shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写 ;key必须为字符串,而值可以是python所支持的数据类型
import shelve
info1={'age':18,'height':180,'weight':80}
info2={'age':73,'height':150,'weight':80}
d=shelve.open('db.shv') #增
d['egon']=info1
d['alex']=info2
d.close()
d=shelve.open('db.shv') #查
print(d['egon']) #{'age': 18, 'height': 180, 'weight': 80}
print(d['alex']) #{'age': 73, 'height': 150, 'weight': 80}
d.close()
d=shelve.open('db.shv',writeback=True) #改
d['alex']['age']=10000
print(d['alex']) #{'age': 10000, 'height': 150, 'weight': 80}
d.close()
6.15 xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,在json还没诞生的黑暗年代,只能选择用xml,至今很多传统公司如金融行业的很多系统的接口还主要是xml
6.151 xml模块举例:
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year updated="yes">2018</year>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year updated="yes">2021</year>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year updated="yes">2021</year>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
查 : 三种查找节点的方式
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
res=root.iter('rank') # 会在整个树中进行查找,而且是查找到所有
for item in res:
print(item) # <Element 'rank' at 0x000002C3C109A9F8>.....
print(item.tag) # 标签名 rank rank rank
print(item.attrib) # 属性 {'updated': 'yes'} {'updated': 'yes'}...
print(item.text) # 文本内容 2 5 69
res=root.find('country') # 只能在当前元素的下一级开始查找。并且只找到一个就结束
print(res.tag)
print(res.attrib)
print(res.text)
nh=res.find('neighbor') # 在res的下一级查找
print(nh.tag)
print(nh.attrib)
cy=root.findall('country') # 只能在当前元素的下一级开始查找, 但是查找到所有
print([item.attrib for item in cy]) #[{'name':'Liechtenstein'},{'name':'Singapore'},{'name':'Panama'}]
改:
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
res=root.iter('year')
for item in res:
item.text=str(int(item.text) + 10)
item.attrib={'updated':'yes'}
tree.write('a.xml') #把更改写入
tree.write('c.xml') #新建一个.xml文件,把更改的结果写入
增:
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
for country in root.iter('country'):
year=country.find('year')
if int(year.text) > 2020:
ele=ET.Element('egon')
ele.attrib={'nb':'yes'}
ele.text='非常帅'
country.append(ele)
country.remove(year) tree.write('b.xml')
python 之 random 模块、 shutil 模块、shelve模块、 xml模块的更多相关文章
- Python 入门基础17 --加密、表格、xml模块
今日内容: 1.hashlib模块:加密 2.hmac模块:加密 3.configparser模块:操作配置文件 4.subprocess模块:操作shell命令 5.xlrd模块:excel 6.x ...
- configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象
1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...
- Python3基础(5)常用模块:time、datetime、random、os、sys、shutil、shelve、xml处理、ConfigParser、hashlib、re
---------------个人学习笔记--------------- ----------------本文作者吴疆-------------- ------点击此处链接至博客园原文------ 1 ...
- Python 入门基础15 --shutil、shelve、log常用模块2、项目结构
今日内容: 一.常用模块 2019.04.10 更新 1.time:时间 2.calendar:日历 3.datatime:可以运算的时间 4.sys:系统 5.os:操作系统 6.os.path:系 ...
- 常用模块:re ,shelve与xml模块
一 shelve模块: shelve模块比pickle模块简单,只有一个open函数,所以使用完之后要使用f.close关闭文件.返回类似字典的对象,可读可写;key必须为字符串,而值可以是pytho ...
- 保存数据到文件的模块(json,pickle,shelve,configparser,xml)_python
一.各模块的主要功能区别 json模块:将数据对象从内存中完成序列化存储,但是不能对函数和类进行序列化,写入的格式是明文. (与其他大多语言交互的类型) pickle模块:将数据对象从内存中完成序列 ...
- Python学习第十二课——json&pickle&XML模块&OS模块
json模块 import json dic={'name':'hanhan'} i=8 s='hello' l=[11,22] data=json.dumps(dic) #json.dumps() ...
- Python—day18 dandom、shutil、shelve、系统标准流、logging
一.dandom模块 (0, 1) 小数:random.random() [1, 10] 整数:random.randint(1, 10) [1, 10) 整数:random.randrange(1, ...
- 函数和常用模块【day06】:xml模块(六)
本节内容 1.简述 2.xml格式 3.xml节点操作 4.创建新的xml文件 一.简述 xml是实现不同语言或者程序之间进行数据交换的协议,跟json差不多,但是json使用起来更简单,不过,古时候 ...
- python 全栈开发,Day25(复习,序列化模块json,pickle,shelve,hashlib模块)
一.复习 反射 必须会 必须能看懂 必须知道在哪儿用 hasattr getattr setattr delattr内置方法 必须能看懂 能用尽量用__len__ len(obj)的结果依赖于obj. ...
随机推荐
- Linux CentOS下安装、配置mysql数据库
假设要在Linux上做j2ee开发.首先得搭建好j2ee的开发环境.包含了jdk.tomcat.eclipse的安装(这个在之前的一篇随笔中已经有具体解说了Linux学习之CentOS(七)--Cen ...
- 光流(optical flow)和openCV中实现
转载请注明出处! ! ! http://blog.csdn.net/zhonghuan1992 光流(optical flow)和openCV中实现 光流的概念: 是Gibson在195 ...
- [Android]Android5.0实现静默接听电话功能
原因: android曾经能够通过AIDL进行静默接听.可是5.0以后就被谷歌给屏蔽了.这时候我们仅仅能通过其它方式实现了. 解决方式: try { Runtime.getRuntime().exec ...
- Release Candidate
RC_百度百科 https://baike.baidu.com/item/RC/7311964?fr=aladdin RC=Release Candidate,含义是"发布候选版" ...
- HTML CSS 编码规范
返璞归真,代码规范也是一门艺术 黄金定律 永远遵循同一套编码规范 -- 可以是这里列出的,也可以是你自己总结的.如果你发现本规范中有任何错误,敬请指正.通过open an issue on GitHu ...
- 几个 PHP 的"魔术常量"
__LINE__ 文件中的当前行号. __FILE__ 文件的完整路径和文件名.如果用在被包含文件中,则返回被包含的文件名.自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符 ...
- poj 1469 COURSES 解题报告
题目链接:http://poj.org/problem?id=1469 题目意思:有 N 个人,P个课程,每一个课程有一些学生参加(0个.1个或多个参加).问 能否使得 P 个课程 恰好与 P 个学生 ...
- 基于HALCON的模板匹配方法总结 (转)
很早就想总结一下前段时间学习HALCON的心得,但由于其他的事情总是抽不出时间.去年有过一段时间的集中学习,做了许多的练习和实验,并对基于HDevelop的形状匹配算法的参数优化进行了研究,写了一篇& ...
- Java 网络处理(net io URL 等)
1. URL 类 URL 类的两个重要方法: openStream():打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream. URL url = new URL(" ...
- MFC显示Mat图片
Opencv在1.0时代,在MFC框架上显示图片可以通过Cvvimage类里的DrawPicToHDC( IplImage *img, UINT ID)方法方便的显示出来,当然当时使用的还是IpIIm ...