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模块的更多相关文章

  1. Python 入门基础17 --加密、表格、xml模块

    今日内容: 1.hashlib模块:加密 2.hmac模块:加密 3.configparser模块:操作配置文件 4.subprocess模块:操作shell命令 5.xlrd模块:excel 6.x ...

  2. configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象

    1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...

  3. Python3基础(5)常用模块:time、datetime、random、os、sys、shutil、shelve、xml处理、ConfigParser、hashlib、re

    ---------------个人学习笔记--------------- ----------------本文作者吴疆-------------- ------点击此处链接至博客园原文------ 1 ...

  4. Python 入门基础15 --shutil、shelve、log常用模块2、项目结构

    今日内容: 一.常用模块 2019.04.10 更新 1.time:时间 2.calendar:日历 3.datatime:可以运算的时间 4.sys:系统 5.os:操作系统 6.os.path:系 ...

  5. 常用模块:re ,shelve与xml模块

    一 shelve模块: shelve模块比pickle模块简单,只有一个open函数,所以使用完之后要使用f.close关闭文件.返回类似字典的对象,可读可写;key必须为字符串,而值可以是pytho ...

  6. 保存数据到文件的模块(json,pickle,shelve,configparser,xml)_python

    一.各模块的主要功能区别 json模块:将数据对象从内存中完成序列化存储,但是不能对函数和类进行序列化,写入的格式是明文.  (与其他大多语言交互的类型) pickle模块:将数据对象从内存中完成序列 ...

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

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

  8. Python—day18 dandom、shutil、shelve、系统标准流、logging

    一.dandom模块 (0, 1) 小数:random.random() [1, 10] 整数:random.randint(1, 10) [1, 10) 整数:random.randrange(1, ...

  9. 函数和常用模块【day06】:xml模块(六)

    本节内容 1.简述 2.xml格式 3.xml节点操作 4.创建新的xml文件 一.简述 xml是实现不同语言或者程序之间进行数据交换的协议,跟json差不多,但是json使用起来更简单,不过,古时候 ...

  10. python 全栈开发,Day25(复习,序列化模块json,pickle,shelve,hashlib模块)

    一.复习 反射 必须会 必须能看懂 必须知道在哪儿用 hasattr getattr setattr delattr内置方法 必须能看懂 能用尽量用__len__ len(obj)的结果依赖于obj. ...

随机推荐

  1. HDU 1060 Leftmost Digit (数学/大数)

    Leftmost Digit Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  2. [转载]php中深拷贝浅拷贝

    转自:http://cnn237111.blog.51cto.com/2359144/1283163 PHP中提供了一种对象复制的操作,clone.语法颇为简单: $a = clone $b; 1.浅 ...

  3. HDU 5371 Hotaru&#39;s problem(Manacher算法+贪心)

    manacher算法详见 http://blog.csdn.net/u014664226/article/details/47428293 题意:给一个序列,让求其最大子序列,这个子序列由三段组成, ...

  4. 2016/05/27 php上传文件常见问题总结

    php上传文件常见问题总结 投稿:hebedich 字体:[增加 减小] 类型:转载 时间:2015-02-03我要评论 这篇文章主要介绍了php上传文件常见问题总结,基本上经常碰到的问题的处理都列了 ...

  5. asp.net连接Access数据库实现登陆功能

    这里话就不多说了,直接演示代码. 连接access数据库首先需要配置web.config <appSettings> <add key="AccessConnString& ...

  6. 为什么java web项目中要使用spring

    1 不使用spring的理由 spring太复杂,不利于调试. spring太复杂,不利于全面掌控代码. spring加载bean太慢. 等等. 2 对不使用spring理由的辩驳 spring io ...

  7. bind_ip

    https://docs.mongodb.com/manual/reference/configuration-options/index.html 192.168.2.* --23T10:: I C ...

  8. the hard problems when writing a great connector; type cohersion, data partitioning and data locality to name a few

    http://rosslawley.co.uk/introducing-a-new=mongodb-spark-connector/

  9. ios 给移动的控件添加点击事件

    前言: 给一个UIView做移动动画,虽然看起来frame在持续改变,但是它的frame已经是最终值了. 也就是说表面看到的动画都是假象,它的真实位置已经是固定的了.所以只有点击在他的真实frame范 ...

  10. 微服务框架go-micro

    微服务框架go-micro https://www.cnblogs.com/li-peng/p/9558421.html 产品嘴里的一个小项目,从立项到开发上线,随着时间和需求的不断激增,会越来越复杂 ...