序列化、time、random、hashlib、sys模块
•很多常用和内置模块,我们只需要掌握他们的用法而暂时不用考虑内部是如何实现的,这些模块大大提升了开发效率 !
1、json模块与pickle模块
•json
如果你有这样的困扰,当希望把一种数据存到硬盘里,但发现只能保存为字符串,再取出来时不能直接被python解释器当作其他数据类型使用,
其实你想完成的事情就是序列化与反序列化的过程,那么json模块和pickle模块可以帮到你。
字典--》特定的字符串或二进制--(编码)--》存到硬盘--(读取解码)—》保存的字符串或二进制——》原数据类型
——-序列化—————————》—持久化--- |||——————|||—---------—》----------反序列化--------
如果你有其他语言的开发经验,那你一定听说或使用过json
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式,采用完全独立于编程语言的文本格式来存储和表示数据。
将内存中的数据类型用json处理后变成json格式的字符串存在硬盘,以后取出来按json的方式解析,可以转回原数据类型进而使用。
优点:所有语言都能识别
缺点: 只支持python的 字典 列表 数字 None 字符串 bool
用法:
import json
dict1 = {"name": '张'}
js_dict1=json.dumps(dict1)
with open('dict1.json','wt',encoding='utf8') as f:
f.write(js_dict1)
with open('dict1.json','rt',encoding='utf8') as f1:
res=f1.read()
dict1=json.loads(res)
print(type(dict1)) # <class 'dict'>
# 方法2
with open('dict1.json','wt',encoding='utf8') as f:
json.dump(dict1,f)
with open('dict1.json','rt',encoding='utf8') as f1:
dict2=json.load(f1)
print(dict2)
json的使用
json格式的文本没有单引号,只有双引号。
•pickle
pickle格式可以支持python的所有数据类型,但不能跨平台使用。
使用方法上,与json没有区别,只是写入文件时是用 b 模式。
import pickle
with open('dict1.picke','wb',) as f:
pickle.dump(dict1,f)
with open('dict1.picke','rb',) as f2:
dict2=pickle.load(f2)
print(dict2)
# ----------------------
dict1_p = pickle.dumps(dict1)
with open('dict1.pkl', 'wb', ) as f:
f.write(dict1_p)
with open('dict1.pkl', 'rb', ) as f1:
dict2 = pickle.loads(f1.read())
print(dict2)
pickle的使用
2、time模块和datetime模块
python用3种形式表示时间:
•时间戳 从1970.1.1至今的秒数
•结构化的时间对象 将时间的 年月日时分秒 星期等属性分开,作为对象供用户使用
•格式化的时间字符 提供时间和自定义格式
•time
import time
print(time.time()) # 时间戳:1487130156.419527
print(time.strftime("%Y-%m-%d %X"))
print(time.localtime()) #本地时区的struct_time
print(time.gmtime()) #UTC时区的struct_time
time的使用
%a Locale’s abbreviated weekday name. %A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. (1) %S Second as a decimal number [00,61]. (2) %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3) %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. 格式化字符串的时间格式
格式化时间字符
三种格式的时间存在如下转换关系,使用对应的方法就可以转换:

#--------------------------按图1转换时间
# localtime([secs])
# 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
time.localtime()
time.localtime(1473525444.037215)
#gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
# mktime(t) : 将一个struct_time转化为时间戳。
print(time.mktime(time.localtime()))#1473525749.0
# strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
# time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
# 元素越界,ValueError的错误将会被抛出。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
# time.strptime(string[, format])
# 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
# tm_wday=3, tm_yday=125, tm_isdst=-1)
#在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
转换方法
补充:sleep(secs) # 线程推迟指定的时间运行,单位为秒。
•datetime
相对于time模块,datetime在获取时间,做时间运算和时间转换上更为方便
import datetime # print(datetime.datetime.now()) #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 # 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)) #时间替换 datetime模块
datetime的用法
3、random模块
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之间的整数 ',[4,5]]))#1或者23或者[4,5] ',[4,5]],2))#列表元素任意2个组合 print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 item=[1,3,5,7,9] random.shuffle(item) #打乱顺序 print(item)
random的使用
练习:用random写一个可以生成指定位数验证码的功能,验证码由大写字母和数字组成。
def code(num=4):
str1 = ""
for i in range(num):
digit0 = str(random.randint(0, 9)) # 生成数字
alpha0 = chr(random.randint(65, 90)) # 生成字母
str0 = random.choice([digit0, alpha0])
str1 += str0
return str1
print(code(5))
生成验证码
4、hashlib模块
hash ,中文:散列,这是一类算法,只要有sha_1、sha_224、sha_256、md5等等
这种算法接收传入的内容,经过运算得到一串hash值,具有以下特点:
•只要传入的值一样,得到的hash值也一样
•几乎不能被反解
•只要使用hash的算法不变,hash值的长度就是固定的,而与传入的值的大小无关
由于这三个特性,hash普遍被应用于 密码传输(将明文密码hash后传输到服务器端保存)、文件校验(校验下载的文件和服务器端是否一致,只需要校验hash值)等用途。
hash的使用方法如下:
import hashlib
h = hashlib.md5()
h.update('''This module implements a common interface to many different secure
hash and message digest algorithms.'''.encode('utf8'))
h.update("加密key".encode('utf8'))
print(h.hexdigest()) # c81547df387cea65942c22adb7077c8f
hash算法虽然几乎不可能被破解,但是对于密码这种不是很长的数据,可以采用穷举法暴力“撞库”,来得到原来的密码:
import hashlib
passwds=[
'alex3714',
'alex1313',
'alex94139413',
'alex123456',
'123456alex',
'a123lex',
]
def make_passwd_dic(passwds):
dic={}
for passwd in passwds:
m=hashlib.md5()
m.update(passwd.encode('utf-8'))
dic[passwd]=m.hexdigest()
return dic
def break_code(cryptograph,passwd_dic):
for k,v in passwd_dic.items():
if v == cryptograph:
print('密码是===>\033[46m%s\033[0m' %k)
cryptograph='aee949757a2e698417463d47acac93df'
break_code(cryptograph,make_passwd_dic(passwds))
模拟撞库
python还有一个hmac模块,也是对数据进行加密的,可以自行了解。
5、sys模块
sys :system,见名知义,它提供了一系列关于系统的功能,这里的系统,对于python开发者来说,就是python解释器。
主要功能有:
# sys.argv # 返回一个列表,第一个元素是脚本路径,拥有列表的增删改查等操作,# #能实现在命令行从程序外部向程序内部传递参数# sys.exit(n) # 退出程序,正常退出时 n=0一般情况下执行到主程序末尾,解释器自动退出,# #但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序# # 表示你可以在主程序中捕获对sys.exit的调用。# sys.version # 获取python解释器的版本信息# sys.path # 环境变量列表,再导入自定义模块时,常用它将模块所在文件夹添加到环境变量# sys.platform # 获取当前系统平台. 如:win32、Linux等。
可以自己写一个在cmd命令行传入文件路径,实现文件复制的功能:
src_path = sys.argv[1]
targe_path = sys.argv[2]
with open(src_path, "rb")as f0, open(targe_path, "wb")as f1:
while True:
data = f0.read(1024)
if not data:
break
f1.write(data)
复制文件
序列化、time、random、hashlib、sys模块的更多相关文章
- python 常用模块之random,os,sys 模块
python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...
- python笔记-1(import导入、time/datetime/random/os/sys模块)
python笔记-6(import导入.time/datetime/random/os/sys模块) 一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其 ...
- python笔记-6(import导入、time/datetime/random/os/sys模块)
一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其它内容待日后有深入理解了再来细说 1.import可以导入的两种不同的内容 1.1 *.py文件结尾的文件 ...
- day25-2 random,os,sys模块
目录 random 为什么要有random模块,random模块有什么用 os 为什么要有os模块,os模块有什么用 sys 为什么要有sys模块,sys模块有什么用 random import ra ...
- Python标准库之Sys模块使用详解
sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. 处理命令行参数 在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称. 使用sy ...
- Python——标准库 Sys模块
---------------------------------------------------------------------------------------------------- ...
- Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)
一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...
- 模块—— 序列化模块、random模块、os模块 、 sys模块、hashlib模块、collections模块
今天我们来说说Python中的模块: 第三方模块 可以下载/安装/使用 第一步:将pip.exe 所在的目录添加到环境变量中第二步:输入pip第三步:pip install 要安装的模块名称 #pi ...
- day13 函数模块之序列化 random 模块 os模块 sys模块 hashlib模块 collections模块
json import json dic = {'k1':'v1','k2':'v2','k3':'v3'} str_dic = json.dumps(dic) #序列化:将一个字典转换成一个字符串 ...
随机推荐
- <Python Text Processing with NLTK 2.0 Cookbook>代码笔记
如下是<Python Text Processing with NLTK 2.0 Cookbook>一书部分章节的代码笔记. Tokenizing text into sentences ...
- Python中的 *args 和 **kwargs
基本概念 Python支持可变参数,最简单的方法莫过于使用默认参数. def test_defargs(one, two=2): # 参数one没有默认值,two的默认值为2 print('Requi ...
- 试试Markdown哈
目录 一级标题 二级标题 三级标题 二级标题? 我擦了? 这什么语法.文字下面加-号,实现二级标题? 看看是几级标题 还真的是二级标题. ...... # 看来四个空格是个,嗯,默认的东西 ??中间是 ...
- explor img file
1, get offset # parted bone-debian----4gb.img GNU Parted 3.1 Using /workspace/bone-debian----4gb.img ...
- Python序列的一点用法
#python的基本语法网上已经有很多详细的解释了,写在这里方便自己记忆一些 序列,顾名思义,是一段数据的有序排列,列表,元组,字符串都是序列的一种,序列有很多BIF(BIF是内建方法,即python ...
- Python基础(条件判断,循环,占位符等)
Python 自动化 系统开发用的语言和自动化脚本可以不同 学习peython可用于: 网路爬虫,数据分,web开发,人工智能,自动化运维,自动化测试,嵌入式,黑客 第三方库比较全 脚本语言:功能单一 ...
- Nginx原理
原理机制 Nginx采用多进程(每个worker进程只对应一个线程)和I/O多路复用机制,实现并发的事件驱动处理: 多路复用即通过一种机制监视多个文件描述符,一旦文件描述符就绪(读写就绪),就可通知程 ...
- 泊爷带你学go -- 经典的继承与接口 简直吊炸天 !
package main import ( "fmt" ) type TeamBase struct { m_TeamId uint64 m_Rid uint32 m_RoomRu ...
- springboot +redis配置
springboot +redis配置 pom依赖 <dependency> <groupId>org.springframework.boot</groupId> ...
- L2-013 红色警报 (25 分)
L2-013 红色警报 (25 分) 战争中保持各个城市间的连通性非常重要.本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报.注意:若该国本来就不完全 ...