大概有123456789个python库

一、时间模块

1. time

import time

​ 时间分为三种格式:

  1. 时间戳: 从1970年到现在经过的秒数(作用: 用于时间间隔的计算)

    print(time.time())
    
  2. 格式化字符串时间: 2020-07-13 21: 39: 00(作用: 用于展示时间)

    print(time.strftime("%Y-%m-%d %H:%M:%S %p"))
    """2020-07-13 21:42:23 PM"""
    print(time.strftime("%Y-%m-%d %X"))
    """2020-07-13 21:42:23"""
    
  3. 结构化时间(作用: 用于单独获取时间的某一部分)

    res = time.localtime()
    print(res)
    """time.struct_time(tm_year=2020, tm_mon=7, tm_mday=13, tm_hour=21, tm_min=44, tm_sec=31, tm_wday=0, tm_yday=195, tm_isdst=0)"""
    print(res.tm_year)
    
    import time
    print(time.asctime)
    

2. datetime

print(datetime.datetime.now())
"""2020-07-13 21:50:04.081180"""

print(datetime.datetime.now() + datetime.timedelta(days=2))
"""2020-07-15 21:51:49.201192"""

print(datetime.datetime.now() + datetime.timedelta(days=-2))
"""2020-07-11 21:52:35.568844"""

print(datetime.datetime.now() + datetime.timedelta(weeks=2))
"""2020-07-27 21:53:22.064504"""

3.时间格式的转换

格式化字符串时间 <=> 结构化时间(strcut_time) <=> 时间戳

# strcut_time ---> 时间戳
s_time = time.localtime()
print(time.mktime(s_time))

# 时间戳 ---> strcut_time
tp_time = time.time()
print(time.localtime(tp_time))

print(time.gmtime())  # 世界标准时间
print(time.gmtime(tp_time))

# strcut_time ---> 格式化字符串时间
s_time = time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S', s_time))

# 格式化字符串时间 ---> strcut_time
print(time.strptime('2020-07-13 21:42:23', '%Y-%m-%d %H:%M:%S'))
"""time.struct_time(tm_year=2020, tm_mon=7, tm_mday=13, tm_hour=21, tm_min=42, tm_sec=23, tm_wday=0, tm_yday=195, tm_isdst=-1)"""

# 格式化字符串时间 ---> 时间戳
s_time = time.strptime('2020-07-13 21:42:23', '%Y-%m-%d %H:%M:%S')
tp_time = time.mktime(s_time) + 7*86400
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tp_time)))
"""2020-07-20 21:42:23"""

二、random 模块

import random
# 取随机数字
print(random.random())  # (0, 1) 大于0小于1之间的小数
print(random.randint(1, 4))  # [1, 3]大于等于1小于等于3之间的整数
print(random.randrange(1, 5))  # [1, 5)大于等于1小于5之间的整数
print(random.choice([1, 'xxx', [333, 4]]))  # 列表中的元素任意取一个
print(random.sample([1, 'xxx', [333, 4]], 2))  # 列表中取出指定个数(2)元素
print(random.uniform(1, 4))  # 取大于1小于4的小数
# 打乱item顺序(洗牌)
item = [1, 2, 3, 4, 5, 6]
random.shuffle(item)
print(item)

应用: 随机验证码

import random


def make_code(size=6):
    res = ''
    for i in range(size):
        res += random.choice([str(random.randint(0, 9)), chr(random.randint(65, 90))])
    return res


print(make_code(4))

三、os 模块

import os

print(os.getcwd())  # 获取当前文件工作路径
# os.chdir('..')  # 修改当前工作路径, 相当于cmd中的cd
print(os.curdir)  # 返回当前目录, 结果为'.'
print(os.pardir)  # 返回上一级目录, 结果为'..'
# print(os.makedirs('dirname1/dirname2'))  # 可递归生成多个目录(文件夹)
# print(os.removedirs('dirname1'))  # 递归的删除空文件夹
# print(os.mkdir('dirname'))  # 生成单级目录: 相当于cmd中的mkdir dirname
print(os.rmdir('dirname'))  # 删除单级空目录, 若目录不为空, 报错
print(os.listdir('dirname'))  # 获取某一个文件夹下所有子文件/子文件夹名字(****常用)
print(os.remove('path'))  #
print(os.rename())  #
print(os.name)  # 显示系统名字
print(os.system(r'dir c:'))  # 运行系统命令
print(os.environ)  # 环境变量 ---> key与value必须都为字符串
# os.path系列 ==============================
print(os.path.abspath())  # 返回绝对路径
print(os.path.getsize('path'))  # 获取文件大小
print(os.path.split('c:\\a\\b\\c\\d.txt'))  # 分割文件和文件夹
"""('c:\\a\\b\\c', 'd.txt')"""
print(os.path.dirname(r'c:\a\b\c\d.txt'))
"""c:\a\b\c"""
print(os.path.basename(r'c:\a\b\c\d.txt'))
"""d.txt"""
print(os.path.isabs(r'c:\a\b\c\d.txt'))
"""True"""
print(os.path.isfile(r'c:\a\b\c\d.txt'))  # 判断时一个文件并且存在
"""False"""
print(os.path.isdir(r'c:\a\b\c'))  # 判断时一个文件夹并且存在
"""False"""
print(os.path.join('a', 'b', 'c', 'd.txt'))  # 拼接文件路径
"""a\b\c\d.txt"""
print(os.path.getatime('path'))  # 返回文件或者目录的最后存取时间
"""a\b\c\d.txt"""
print(os.path.getctime('path'))  # 返回文件或者目录的最后修改时间
"""a\b\c\d.txt"""
print(os.path.normcase(r'c:/a/b\c'))
"""规范化路径 ---> c:\a\b\c"""


from pathlib import Path
res = Path(__file__)
print('====', res.parent)

四、sys模块

import sys
print(sys.path)
print(sys.argv)  # 用于在python程序内接收外部传入的参数


打印进度条
res = ''
for i in range(50):
    res += '#'
    print('\r[%-50s]' % res, end='')  # \r 回到行首
    
# 升级版
import time
total_size = 3333333
recv_size = 0
while recv_size < total_size:
    if total_size - recv_size >= 1024:
    	recv_size += 1024
    else:
        recv_size = total_size - recv_size
    time.sleep(0.1)
    percent = recv_size/total_size
    res = int(50*percent) * '#'
    print(f'\r[{res}-50s] {int(percent*100)}',  end='') 

五、shutil 模块

import shutil  # 针对文件的操作

shutil.copyfileobj(open('old_fime', 'r'), open('new_file', 'w'))
shutil.copyfile('f1', 'f2')
shutil.copymode(src, dst)  # 仅拷贝权限
shutil.copy(src, dst)  # 拷贝文件和权限
shutil.copy2(src, dst)  # 拷贝文件和状态信息
shutil.copytree()  # 递归拷贝文件夹
shutil.rmtree()  # 递归删除文件夹
shutil.move()  # 递归拷贝文件夹

六、json

序列化: 把内存的数据类型转换成一个特定格式的内容, 该格式的内容可以用于存储汇总传输给其他平台使用

内存中的数据类型 —> 序列化 —> 特定的格式

内存中的数据类型 <— 反序列化 <— 特定的格式

序列化作用: 1. 可用于存储(可以是一种专用的格式) 2. 传输给其他平台使用(应该是一种通用, 能被所有语言识别的格式)

import json
res = json.dumps(True)
print(res, type(res))
"""true"""
res = json.dumps([1, '111', True, False])
print(res, type(res))
"""[1, "111, true, false]"""

# 写入文件
with open('file_name', mode='wt', encoding='utf-8') as f:
    json.dump([1, '111', True, False], f)

# 反序列化
l = json.loads(res)
print(l, type(l))

# 读取文件
with open('file_name', mode='rt', encoding='utf-8') as f:
    print(json.load(f))

猴子补丁: 在入口文件加上

import json
import ujson

def monkey_patch_json():
    json.__name__ = 'ujson'
	json.dumps = ujson.dumps
	json.loads = ujson.loads
    
    
monkey_patch_json()

七、pickle 模块

import pickle
res = pickle.dumps({1, 2, 3, 4})
print(res, type(res))
"""b'\x80\x03cbuiltins\nset\nq\x00]q\x01(K\x01K\x02K\x03K\x04e\x85q\x02Rq\x03.' <class 'bytes'>"""

s = pickle.loads(res)
print(s, type(s))
"""{1, 2, 3, 4} <class 'set'>"""

八、configarser 模块

import configarser  # 配置文件格式

九、hash 模块

​ 哈希是一类算法: 接收传入的内容, 经过运算得到一串哈希值

​ hash值的特点:

  1. 只要传入的内容一样, 得到的hash值必然一样

  2. 不能由hash值反解成内容

  3. 只要使用的hash算法不变, 无论校验内容有多大, 得到的hash值长度是固定的

​ 用途: 特点2用于对密码进行加密, 特点1, 3用于文件的完整性校验

# -*- encoding: utf-8 -*-
import hashlib

m = hashlib.md5()

m.update('xxxx'.encode('utf-8'))
m.update('122'.encode('utf-8'))
res = m.hexdigest()
print(res)
"""
运行结果: 
e07730387186946afdf87934bdd5db57
"""

# 文件完整性校验
with open('../log/网站访问日志.txt') as f:
    # 校验所有文件内容 ---> 校验速度慢
    for line in f:
        m.update(line.encode('utf-8'))
    print(m.hexdigest())
    """
    运行结果: 
    5ea020631ada4084044b0a8e2a60818a
    """
    
    # 只校验前2000 ---> 校验速度快, 但是有可能相同
    read_txt = f.read(2000)
    m.update(read_txt.encode('utf-8'))
    print(m.hexdigest())

    # 随机取几段文字 ---> 校验速度快, 大概率所校验的数据是完整的
    f.seek()
    f.read()


# 密码: 密文传输
# 撞库

# -*- encoding: utf-8 -*-
import hashlib

cryptograph = 'e07730387186946afdf87934bdd5db57'
# 制作密码字典
passwds = ['12ssw', 'de2de2', 'd31de']
dic_p = {}
for p in passwds:
    res = hashlib.md5(p.encode('utf-8'))
    dic_p[p] = res.hexdigest()

# 模拟撞库获得密码
for k, v in dic_p.items():
    if v == cryptograph:
        print(f'撞库成功, 明文密码是: {k}')
        break


# 提升撞库成本 ---> 密码加盐

import hashlib
m = hashlib.md5()
m.update('1sew'.encode('utf-8'))
m.update('passwd'.encode('utf-8'))
m.update('nvfinda'.encode('utf-8'))
print(m.haxdigest())
	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值