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. 关于从 coding 拉项目的操作

    介绍:coding是托管代码的仓库   sourceTree 是把代码提交到coding的界面化工具 1.通过百度 登录coding账号

  2. 基于jquery 全选、反选、各行换色、单击行选中事件实现代码

    <script language="javascript"> $(document).ready(function(){ //各行换色 $('table tr:odd' ...

  3. Arcgis Engine(ae)接口详解(2):featureClass查询

    //属性查询~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //IQueryFilter代表查询条件,QueryFilterClass代表只限于属性查询(就是没有空间查询) ...

  4. MYiSAM和InnoDB引擎区别(mysql)

    MyISAM 1.读取速度快. 2.※更新时锁整个表. 3.占用资源少. 4.适合读多写少的业务. 5.※不支持事务.   InnoDB 1.读取速度一般. 2.※更新时锁当前行. 3.占用资源高. ...

  5. CString转换成char *字符串问题

    buf = (LPSTR)(LPCTSTR)str;      ==>     buf 显示的是第一个字符 strcpy(pNumber,strNumber);      ==>    e ...

  6. 0 lrwxrwxrwx. 1 root root 13 Nov 20 12:44 scala -> scala-2.12.4

    符号链接的文件属性相同,真正的权限属性由符号链接所指向的实际文件决定.

  7. MFC中CAsyncSocket和CSocket

    原文链接:https://blog.csdn.net/libaineu2004/article/details/40395917 摘要部分重点: 1.CAsyncSocket类逐个封装了WinSock ...

  8. #1241 : Best Route in a Grid

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定一个N行N列的非负整数方阵,从左上角(1,1)出发,只能向下或向右走,且不能到达值为0的方格,求出一条到达右下角的最佳 ...

  9. MYSQL进阶学习笔记三:MySQL流程控制语句!(视频序号:进阶_7-10)

    知识点四:MySQL流程控制语句(7-10) 选择语句: (IF ELSE ELSE IF CASE 分支)IFNULL函数 IF语法: 语法规则: IF search_condition THEN ...

  10. iOS——多线程编程详细解析

    基本定义: 程序:由代码生成的可执行应用.(例如QQ.app) 进程:一个正在运行的程序可以看做是一个进程. (例如:正在运行的QQ 就是一个进程),进程拥有独立运行所需要的全部资源. 线程: 程序中 ...