常用模块
- time
import time
# 时间戳:从时间元年到现在经过的秒数
# 时间元年:1970年1月1日 00:00
# 获取时间戳
print(time.time()) # 1586180444.5316331
# 获取格式化时间对象
print(time.gmtime()) # 格林尼治时间(GMT)
# time.struct_time(tm_year=2020, tm_mon=4, tm_mday=6, tm_hour=13, tm_min=51, tm_sec=19, tm_wday=0, tm_yday=97, tm_isdst=0)
print(time.localtime()) # 当地时间
# time.struct_time(tm_year=2020, tm_mon=4, tm_mday=6, tm_hour=21, tm_min=55, tm_sec=4, tm_wday=0, tm_yday=97, tm_isdst=0)
# 格式化时间对象和字符串之间的转换
s = time.strftime('%Y-%m-%d %H:%M:%S')
print(s)
# 时间字符串转换成时间对象
time_obj = time.strptime('2020 4 1', '%Y %m %d')
print(time_obj)
# 时间对象转化成时间戳
print(time.mktime(time.localtime()))
# time.sleep()
time.sleep(1) # 暂停当前进程1秒
for i in range(5):
print(time.strftime('%Y-%m-%d %H:%M:%S'))
time.sleep(2)
- datetime
import datetime
print(datetime.datetime.now()) # 获取当前时间
now_time = datetime.datetime.now()
print(now_time + datetime.timedelta(weeks=2)) # 两周后 -2则是两周前
print(now_time + datetime.timedelta(days=-4)) # 4天前
print(now_time + datetime.timedelta(hours=6, minutes=-9, seconds=2)) # 6小时后,9分钟前,2秒后
current_time = datetime.datetime(1996, 6, 2, 13, 8, 45)
print(current_time.replace(year=1999, month=9, day=30, hour=2, minute=45, second=3)) # 修改时间
print(datetime.datetime.fromtimestamp(1432132131)) # 时间戳转化为时间
- os
import os
# 和文件相关
os.remove(r'xxx.xx') # 删除文件
os.rename('a.txt', 'b.txt') # 重命名文件/目录
print(os.stat('path/file')) # 获取文件/目录信息
# 和文件夹相关
os.makedirs('aaa/bbb/ccc') # 可生成多层递归目录
os.removedirs('aaa/bbb/ccc') # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') # 生成单级目录
os.rmdir('dirname') # 删除单级目录
os.listdir('dirname') # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
# 和路径相关
print(os.path.abspath('path')) # 获取path的绝对路径
print(os.path.split('path')) # 将path分割成目录和文件名二元组返回
print(os.path.dirname('path')) # 返回path的目录
print(os.path.basename('path')) # 返回path最后的文件名。如何path以/或结尾,那么就会返回空值,即os.path.split(path)的第二个元素
print(os.path.exists('path')) # 判断path是否存在
print(os.path.isabs('path')) # 判断path是否是绝对路径
print(os.path.isfile('path')) # 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir('path') # 如果path是一个存在的目录,则返回True。否则返回False
os.path.getsize('path') # 返回path的大小
print(os.environ) # 获取系统环境变量
- sys
import sys
print(sys.argv) # 命令行参数List,第一个元素是程序本身路径
# print(sys.exit(n)) # 退出程序,正常退出时exit(0),错误退出sys.exit(1)
print(sys.version) # 获取Python解释程序的版本信息
print(sys.path) # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
print(sys.platform) # 返回操作系统平台名称
-
hashlib
-
文件加密
import hashlib # md5只是hashlib模块中的其中一种加密算法,也是最常用的,其他加密算法的用法和md5一样 # 普通加密 ret = hashlib.md5() ret.update('123'.encode('utf-8')) print(ret.hexdigest()) # 202cb962ac59075b964b07152d234b70 # 加盐加密 ret = hashlib.md5("i'm salt".encode('utf-8')) # i'm salt在这里就是加的一个固定的盐 ret.update('123'.encode('utf-8')) print(ret.hexdigest()) # 8c4fb7bf681156b52fea93442c7dffc9 # 动态的盐 username = 'jason' ret = hashlib.md5(username[::2].encode('utf-8')) ret.update('123'.encode('utf-8')) print(ret.hexdigest()) # 0c52973c7d260c35cd3755f688678002
-
文件校验
# 2.文件校验 import hashlib import time def wrapper(f): # 装饰器,测试不同方法校验时间 def inner(*args, **kwargs): start_time = time.time() re = f(*args, **kwargs) end_time = time.time() print(f'用时{end_time - start_time}') return re return inner # 简单实现文件校验 @wrapper def func1(file): with open(file, 'rb') as f1: ret = hashlib.md5() ret.update(f1.read()) return ret.hexdigest() # 分段式校验,一行行校验 @wrapper def func2(file): with open(file, 'rb') as f2: ret = hashlib.md5() for line in f2: ret.update(line) return ret.hexdigest() # 分段式校验,设定字节长度校验 @wrapper def func3(file): with open(file, 'rb') as f3: ret = hashlib.md5() while 1: content = f3.read(1024) if content: ret.update(content) else: return ret.hexdigest() print(func1('pycharm-professional-2019.3.4.exe')) print(func2('pycharm-professional-2019.3.4.exe')) print(func3('pycharm-professional-2019.3.4.exe'))
-
-
json 最常用的序列化模块
序列化模块就是将一个常见的数据结构转化成一个特殊的序列,并且这个特殊的序列还可以反解回去。它的主要用途:文件读写数据,网络传输数据。
json序列化只支持部分Python数据结构:dict,list, tuple,str,int, float,True,False,None
1.用于网络传输dumps、loads
import json
dic1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
str_dic = json.dumps(dic1) # 序列化:将一个字典转换成字符串类型
print(type(str_dic), str_dic) # json转换完的字符串类型的字典中的字符串是由""表示的
dic2 = json.loads(str_dic) # 反序列化:将一个字符串类型的字典转化成字典类型
print(type(dic2), dic2) # 要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
2.用于文件读写dump、load
import json
f1 = open('json_file', 'w')
dic1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
json.dump(dic1, f1) # dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f1.close()
f2 = open('json_file')
dic2 = json.load(f2) # load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f2.close()
print(type(dic2), dic2)
3.json 格式化输出
import json
dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
json_dic = json.dumps(dic, sort_keys=True, indent=4, separators=(',', ':'), ensure_ascii=False)
print(json_dic)
-
pickle
pickle和json用法一样
json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换 -
collections
# namedtuple
from collections import namedtuple as nt
Point = nt('Point', ['x', 'y'])
r = Point(2, 3)
print(r)
print(r.x)
print(r.y)
# Counter
from collections import Counter
c = Counter('12312342343152321454132341234')
print(c)