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. struts(转)

    配置文件的优先级 在struts2中一些配置(比如常量)可以同时在struts-default.xml(只读性),strtus-plguin.xml(只读性),struts.xml,struts.pr ...

  2. CSS属性中Display与Visibility的不同

    大多数人很容易将CSS属性display和visibility混淆,它们看似没有什么不同,其实它们的差别却是很大的.visibility属性用来确定元素是显示还是隐藏,这用visibility=&qu ...

  3. C++类中使用new及delete小例子

    //默认复制构造函数的不足//尽管有默认的复制构造函数来解决一般对象与对象之间的初始化问题, 但是在有些情况下我们必须手动显式的去定义复制构造函数, 例如: #include <iostream ...

  4. 【配置关系】—Entity Framework实例详解

    实体间的关系,简单来说无非就是一对一.一对多.多对多,根据方向性来说又分为双向和单向.Code First在实体关系上有以下约定: 1. 两个实体,如果一个实体包含一个引用属性,另一个实体包含一个集合 ...

  5. Jquery根据name取得所有选中的Checkbox值

    var spCodesTemp = "";            $('input:checkbox[name=supNO]:checked').each(function (i) ...

  6. RabbitMQ Connector

    https://ci.apache.org/projects/flink/flink-docs-master/dev/connectors/rabbitmq.html RabbitMQ Source ...

  7. How do I set the timeout for a JAX-WS webservice client?

    How do I set the timeout for a JAX-WS webservice client? up vote58down votefavorite 27 I've used JAX ...

  8. STM32低功耗模式与烟雾报警器触发信号电路设计

    1.STM32的3种低功耗模式 STM32有3种低功耗模式,分别是睡眠模式.停机模式和待机模式. 2.STM32在不同模式下的电流消耗 a.工作模式  消耗电流在27mA至36mA之间. b.睡眠模式 ...

  9. Dom解析XMl文档

    XMl文档 <?xml version = "1.0" encoding = "UTF-8"?> <books> <book bo ...

  10. 初探linux子系统集之led子系统(三)【转】

    本文转载自:http://blog.csdn.net/eastmoon502136/article/details/37822837 世界杯结束了,德国战车夺得了大力神杯,阿根廷最终还是失败了.也许3 ...