day8学python

此博内容:

1.shelve模板  存储数据

2.shutil 模板  用作拷贝/删除/压缩文件(使用便捷)

3.hashlib 模板  加密文件

4.re模板

============================================================

  shelve模板

以字符串方式读取 存储各种数据 用get函数调用

import shelve
d=shelve.open('shelve_test')
name=[21,"3","Er"]
id={23:"sd",3:{232:34}}
d["name"]=name          #直接存入各种数据
d["id"]=id
print(d.get("name"))    #用get函数调用
print(d.get("id"))
d.close()

  shutil 模板

以模板方式读写文件,copy,删除,压缩文件

import shutil
f1=open("歌词",encoding="utf-8")
f2=open("hi","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)       #拷贝文件

shutil.copyfile("hi","歌词")       #等同于上面方法 自动打开文件
shutil.copytree("源文件","目标地址")                #递归的拷贝文件
shutil.rmtree("要删除的文件名")    #方便的删除
shutil.make_archive("压缩成的名字","zip","路径")    #压缩文件

   

  hashlib模板

以MD5,sha256等函数方式加密文件

#加密MD5形式    sha1/sha256
import hashlib
m=hashlib.md5()
m.update("hell01你好".encode(encoding="utf-8"))
print(m.hexdigest())        #得到hello1加密
m.update("hello2 你好".encode(encoding="utf-8"))
print(m.hexdigest())        #得到hello1hello2加密

  re模板(符号+ 代表所有满足符号的字符)

1.match()      //同2 但使用少 (过时)

re.match("符号","cc123nice")
符号可填:
1.‘.’一个任意字符
2.str\d 字符串加后面一个数字
3. $ 匹配到字符结尾
4.'\D'匹配非数字
5.'\w'匹配[A-Za-z0-9]
6.'\W'匹配与5相反

2.search()      //搜索匹配的字符(仅一次 找到即返回

re.search("c[a-z1-9]+e","cc123nice")
符号亦可填 搜索开头+【条件】+(匹配次数)+搜索结尾

3.findall()        //同2但 查找所有满足的字符

4.split()        //按要求分割字符串

split("条件",str)将字符串按数字拆分
re.split("[0-9]+","asdas12few4wqe23")

5.sub()        //按要求替换字符串

  re.sub("条件","替换的对象",str,count=2) 将str中按条件替换成替换的对象

re.sub("[0-9]","|","absdasd342fwef32fe")

猜你喜欢

转载自www.cnblogs.com/cc123nice/p/10513993.html