美文网首页
day21-常用模块(1)

day21-常用模块(1)

作者: 天行_b6d0 | 来源:发表于2020-08-04 16:38 被阅读0次

一、json和pickle模块

1、什么是序列化与反序列化

内存中某一类的数据---------------》特殊的格式
内存中某一类的数据《---------------特殊的格式

2、为何要序列化
  • 1、存档:把内存中的数据持久化到硬盘

  • 2、跨平台交互数据

    在python中:
      存档>>>>推荐用pickle格式
      跨平台交互>>>>推荐用json格式

3、如何序列化
3.1:low的序列化与反序列化方式

1.序列化

items=["无尽之刃","蝴蝶刀","RPG"]


dic_str=str(items)

with open('db.txt',mode='wt',encoding="utf-8") as f:
    f.write(dic_str)

2.反序列化

with open('db.txt',mode='rt',encoding='utf-8') as f:
    data=f.read()  # '["无尽之刃","蝴蝶刀","RPG"]'

    items=eval(data)
    print(items[0])
3.2:json
  • 优点:跨平台交互数据
  • 缺点:无法识别所有的python数据类型
    注意:json格式的字符串里不能包含单引号
    import json

序列化方式一:

t={"a":1,"b":2}  # 字典=======>>>json格式的字符串:"[1,2,3]"

res=json.dumps(t)
print(res,type(res))

with open("a.json",mode='wt',encoding='utf-8') as f:
    f.write(res)

json反序列化方式一:

with open("a.json",mode='rt',encoding='utf-8') as f:
    data=f.read()
    dic=json.loads(data)
    print(dic,type(dic))

res=json.loads('{"k1":111}')
print(res['k1'])

json序列化方式二:

t={"a":1,"b":2}  # 字典=======》json格式的字符串:"[1,2,3]"


with open("b.json",mode='wt',encoding='utf-8') as f:
    json.dump(t,f)

json反序列化方式二:
with open("b.json",mode='rt',encoding='utf-8') as f:
    dic=json.load(f)
    print(dic,type(dic))
3.3:pickle
  • 优点:可以识别所有python类型
  • 缺点:只能用于python中,无法跨平台交互
import pickle

s = {1,2,3,4,5}

res=pickle.dumps(s)
# print(res,type(res))
with open('a.pkl',mode='wb') as f:
    f.write(res)


with open('a.pkl',mode='rb') as f:
    data=f.read()
    s=pickle.loads(data)
    print(type(s))

二、hashlib模块

hash是一种算法(md5\sha256\sha512等),我们为该算法传入内容,该算法会计算得到一串hash值
hash值具备以下三个特点:
  1、如果传入的内容一样,并且采用hash算法也一样,那么得到个hash值一定是一样的
  2、hash值的长度取决于采用的算法,与传入的文本内容的大小无关
  3、hash值不可逆

python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密:

import hmac
h1=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h1.update('world'.encode('utf-8'))

print(h1.hexdigest())

要想保证hmac最终结果一致,必须保证:
1:hmac.new括号内指定的初始key一样
2:无论update多少次,校验的内容累加到一起是一样的内容

操作一

import hmac
h1=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h1.update('world'.encode('utf-8'))

print(h1.hexdigest()) # 0e2564b7e100f034341ea477c23f283b

操作二

import hmac
h2=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h2.update('w'.encode('utf-8'))
h2.update('orld'.encode('utf-8'))

print(h1.hexdigest()) # 0e2564b7e100f034341ea477c23f283b

三、time&datatime模块

1、在Python中,通常有这几种方式来表示时间:
  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
import time
print(time.time())  # 时间戳:1596092875.1012611
print(time.strftime("%Y-%m-%d %X"))  # 格式化的时间字符串:'2020-07-30 15:07:55'
print(time.localtime())  # 本地时区的struct_time
print(time.gmtime())  # UTC时区的struct_time

其中计算机认识的时间只能是'时间戳'格式,而程序员可处理的或者说人类能看懂的时间有: '格式化的时间字符串','结构化的时间' ,它们之间的转换关系为:

时间格式转换图.png 转换图2.png
2、datatime
# 时间加减
import time
import datetime

print(datetime.datetime.now()) #返回 2020-07-30 15:16:04.005351
print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2020-07-30
print(datetime.datetime.now() )
print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

c_time  = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换

四、random模块

import 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.927109612082716 
 
 
item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)
一个生成随机验证码的函数:
import random

# print(chr(65))  # 转换后为A
# print(chr(90))  # 转换后为Z
def identify_num(length = 5):
    res = ""
    for i in range(length):
        s1 = str(random.randint(0,9))
        s2 = chr(random.randint(65,90))
        res += random.choice([s1,s2])
    print(res)
identify_num()

五、os模块

os模块是和操作系统交互的一个接口

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

六、sys模块

  • sys.argv 命令行参数List,第一个元素是程序本身路径
  • sys.exit(n) 退出程序,正常退出时exit(0)
  • sys.version 获取Python解释程序的版本信息
  • sys.maxint 最大的Int值
  • sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
  • sys.platform 返回操作系统平台名称

相关文章

  • day21-常用模块(1)

    一、json和pickle模块 1、什么是序列化与反序列化 内存中某一类的数据---------------》特殊...

  • nginx 2

    1 nginx 常用模块整理 nginx 常用模块整理1 http核心模块 ngx_http_core_modu...

  • Day13 作业

    1.常用的math模块中的方法 2.常用的calendar模块中的方法 3.常用的time模块中的方法 4.常用的...

  • Python常用模块

    Python常用模块之time模块 Python常用模块之os模块 Python常用模块之sys模块 Python...

  • 1-Ansible常用模块之包管理模块:yum_reposito

    1-Ansible常用模块-yum_repository模块 一、概述 yum_repository 模块可以帮助...

  • python基础学习(三)

    常用模块 String模块 数学模块 随机模块 OS模块 os.path模块 re模块 常用函数及操作 列表操作 ...

  • nginx常用模块

    nginx常用模块 1、日志模块 ngx_http_log_module 2、压缩传输模块 ngx_http_gz...

  • PyMoTW-3 python常用模块简介

    PyMoTW介绍python中的常用模块,此文章为PyMoTW下的python3的常用模块学习笔记。 1. Tex...

  • Node(3)

    一、模块系统 1.什么是模块 Node.js中常用的核心模块有: http模块 fs文件系统模块 url模块 pa...

  • Nginx配置referer校验,实现简单的防盗链详解

    1、Nginx Referer模块 nginx模块ngx_http_referer_module通常用于阻挡来源非...

网友评论

      本文标题:day21-常用模块(1)

      本文链接:https://www.haomeiwen.com/subject/akirrktx.html