模块 一

2021-02-23  本文已影响0人  吃可爱长大鸭

json与pickle序列化模块

'''
1. 什么是序列化
    序列化就是将内存中的数据类型转成另外一种格式

    即:
        字典---------序列化--------->其他的格式--------------->存到硬盘
        硬盘---读取---->其他格式----------反序列化-------->字典

2. 为什么要序列化
    1. 持久保存程序的运行状态
    2. 数据的跨平台交互



3. 如何序列化
    json:
        优点: 这种格式是一种通用的格式,所有编程语言都能识别
        缺点: 不能识别所有python类型
        强调:json格式不能识别单引号

    pickle
        优点: 能识别所有python类型
        缺点: 只能被python这门编程语言识别

'''
# json模块

import json

dic={'k1':True,'k2':10,'k3':'egon','k4':'你好啊',}
# 序列化
dic_json=json.dumps(dic)
print(dic_json)

# 持久化
with open('a.json',mode='wt',encoding='utf-8') as f:
    f.write(dic_json)

# 序列化+持久化
with open('a.json',mode='wt',encoding='utf-8') as f:
        json.dump(dic,f)


# 从文件读取json格式化字符串
with open('a.json',mode='rt',encoding='utf-8') as w:
    dic_json=w.read()
# 反序列化
dis=json.loads(dic_json)
print(dis)

# 反序列化+持久化
with open('a.json',mode='rt',encoding='utf-8') as w:
    f=json.load(w)
    print(f)

time与datetime时间模块

# 时间戳
import time
print(time.time())

# 格式化字符串
print(time.strftime('%Y-%m-%d %H:%M:%S %p'))

# 结构化时间对象
print(time.localtime())
print(time.localtime().tm_hour)   #小时
print(time.gmtime())

import datetime
# 获取当前时间
print(datetime.datetime.now())
# 时间戳----->格式化字符串
print(datetime.datetime.fromtimestamp(12321312312))

#计算时间
print(datetime.datetime.now() + datetime.timedelta(days=3))

random随机模块

#  生成随机字母数字
import random
def ouuth(size=10):
    res=''
    for i in range(size):
        lll=str(random.randint(0,9)) # 数字
        kkk=chr(random.randint(65,90)) #小写字母
        sss=chr(random.randint(97,122)) #大写字母
        res+=random.choice([lll,kkk,sss]) 
    return res
print(ouuth(15))

hashlib 校验模块

#校验模块 算法MD5
import hashlib

pwd=input('请输入:')
m=hashlib.md5()
m.update('天王盖地虎'.encode('utf-8'))
m.update(pwd.encode('utf-8'))
m.update('宝塔镇河妖'.encode('utf-8'))
print(m.hexdigest())

shevle(python 序列化)模块

# 序列化 无法跨平台
 import shelve

s = shelve.open('test.she')
 s["dis"]= {'age':20}

sys系统模块

# 系统模块
import  sys
sys.path()

# 当你要开发一款基于CMD的程序时 就需要使用这个属性了   因为一些操作系统没有界面  只能通过CMD来使用
sys.argv()

os系统模块

import os
#创建多级目录
os.makedirs("a/b")
# 当前执行文件所在的文件夹路径
print(os.getcwd())
# 创建单集目录
os.mkdir("a")
# 更改名字
os.rename()
# 删除文件
os.remove()
# 获取系统命令
os.system(r'"D:\windons软件\qq\Tencent\QQ\Bin\QQScLauncher.exe"')
print(os.environ)
# 获取当前目录的 字符串表现方式   .
print(os.curdir)
# 获取当前目录的 字符串表现方式   ..
print(os.pardir)
# 获取换行符
print(os.linesep)
# 修改当前目录
os.chdir(r"E:\学习目录\练习\a")

subprocess子进程模块

"""
    subprocess 翻译为子进程
    进程指的是 正在运行的程序
    子进程  是由另一个正在运行程序启动的程序  例如 qq聊天 点击了一个连接  打开了浏览器 那么浏览器称之为qq的子进程

    为什么使用子进程 ?  当我们有一个任务需要处理 而自己的程序无法处理 所以需要开启另一个程序

    例如 在python 想要获取所有的进程(任务列表)信息
"""
# dir 表示要执行命令
# shell 表示dir是一个命令
# stdout指定输出管道
# 管道是什么?   相当于生活中的水管 水可以通过管道 从一个地方流到另一个地方
# 在程序中  数据相当于水   管道的作用,就从一个进程中把数据传输到另一个进程
# 本质上是读写同一个文件
import subprocess
# 启动一个tasklist子进程 指定输出结果到管道中
p1 = subprocess.Popen("tasklist",shell=True,stdout=subprocess.PIPE)

p2 = subprocess.Popen("findstr cmd", # 要执行的指令
                      shell=False,# 第一个参数是否是一个指令
                      stdin=p1.stdout, # 指定输入管道
                      stdout=subprocess.PIPE,#指定输出管道
                      stderr=subprocess.PIPE) # 表示错误管道   当进程执行出错时 可以在错误管道中获取结果

# 读取p2进程的结果
print(p2.stdout.read())
print(p2.stderr.read().decode("GBK"))
# 总结 当你需要在python中启动一个子进程 并且它进行数据交互时就使用subprocess

congigparser修改配置文件模块

import configparser
#创建一个解析器
cfg = configparser.ConfigParser()
#读取名为test.cfg的配置文件
cfg.read("test.cfg",encoding='utf-8')
#获取分区
print(cfg.sections())


#获取分区下的配置文件
username = cfg.get("mysql","username")
print(username)

password = cfg.get("mysql","password")
print(password)
print(type(password))

lock = cfg.getboolean("mysql","lock")
print(type(lock))
print(lock)

#以下三个函数帮助你封装了类型转换
cfg.getboolean()
cfg.getint()
cfg.getfloat()

#修改文件内容
import configparser

cfg = configparser.ConfigParser()
cfg.read("test.cfg",encoding='utf-8')

cfg.set("mysql","lock","true")
with open('test.cfg',mode='wt',encoding='utf-8') as f:
    cfg.write(f)

import configparser

cfg = configparser.ConfigParser()
cfg.read("test.cfg",encoding='utf-8')
# 添加新的分区
cfg.add_section("新分区")
# 添加新的选项  port 值为3306
cfg.set("mysql","port","3306")

with open('test.cfg',mode='wt',encoding='utf-8') as f:
    cfg.write(f)

#删除
import configparser

cfg = configparser.ConfigParser()
cfg.read("test.cfg",encoding='utf-8')

cfg.remove_section("新分区")

cfg.remove_option("mysql","port")

with open('test.cfg',mode='wt',encoding='utf-8') as f:
    cfg.write(f)

shutil拷贝模块

# 拷贝模块
shutil.copyfile(r"E:\学习目录\练习\模块.py",r"E:\学习目录\练习\模块2.py")

# 压缩文件  支持的格式 zip 和tar
shutil.make_archive("模块.py","zip",r"E:\学习目录\练习")

# 解压文件
shutil.unpack_archive(r"E:\学习目录\练习\模块.py.zip",r"E:\学习目录\练习\解压文件",r"zip")
上一篇 下一篇

猜你喜欢

热点阅读