Python全栈开发 day5 - 模块&包

一、模块 & 包

在Python 中,一个.py文件称为一个模块。Python中模块有三种:Python 标准库、第三方模块、自定义模块。

Python 包由一个或多个.py文件组成,必须存在一个 __init__.py 文件

1. 模块导入方法

(1)import

(2)from...import...

(3)from...import *

二、常用模块

1. time 模块

import time

time.sleep(3)
print(time.time())  # 当前时间戳
print(time.localtime())     # 返回结构化时间对象,当地时间
print(time.localtime().tm_hour)
print(time.gmtime(2424242344))        # 返回结构化时间对象,国际标准时间
print(time.mktime(time.localtime()))    # 将结构化时间转为时间戳
print(time.strftime("%Y-%m-%d %X", time.localtime()))    # 将结构化时间转为字符串,%X 相当于 %H:%M:%S
print(time.strptime("2018-08-05 10:09:12", "%Y-%m-%d %X"))     # 将字符串时间转换为结构化时间
print(time.asctime(time.localtime()))   # 将结构化时间转化为固定格式时间
print(time.ctime(time.time()))   # 将时间戳转化为固定格式时间

2. random 模块

import random

print(random.random())      # 0-1 随机数
print(random.randint(3, 456))   # 3-456 随机数
print(random.randrange(3, 56))   # [3, 56) 随机数
print(random.choice([1, 3, 4, 5]))   # 随机输出 [1, 3, 4, 5] 中任一值
print(random.sample([1, 3, 4, 5], 2))   # 随机输出 [1, 3, 4, 5] 中两个值
print(random.uniform(1, 3))   # 随机输出 1-3 的浮点数
li = [34, 1, 4, 6]
random.shuffle(li)  # 打乱 li 中的值
print(li)


# 生成随机验证码
def v_code():
    code = ""
    for i in range(5):
        num = random.randint(0, 9)
        char = chr(random.randint(65, 122))
        s = str(random.choice([num, char]))
        code += s
    return code

print(v_code())

3. sys 模块

import sys

print(sys.version)      # 获取Python 解释器版本
print(sys.path)         # 返回模块的搜索路径
print(sys.platform)     # 返回操作平台名称
print(sys.exit(0))      # 退出程序,0 正常退出

4. os 模块

import os

print(os.getcwd())  # 获取当前工作目录
print(os.curdir)    # 返回当前目录
os.chdir("test")  # 改变当前工作目录,相当于 shell 下的cd
os.makedirs("../test1/test1")     # 生成多层递归目录
os.removedirs("../test1/test1")     # 递归删除空目录,若上一级目录也为空,删除
os.mkdir("test2")     # 生成单级目录
os.rmdir("test2")       # 删除单级空目录
print(os.listdir())     # 列出指定目录下的所有文件和目录,包括隐藏文件,并以列表方式打印
os.remove("test.txt")   # 删除一个文件
os.rename("test1", "test11")    # 重命名文件或目录

print(os.stat("sss.py"))    # 获取文件或目录信息
print(os.sep)   # 输出操作系统特定的路径分隔符 windows \\ ,linux /
print(os.linesep)   # 输出当前平台使用的行终止符
print(os.pathsep)   # 输出用于分割文件路径的字符串
os.system("adb devices")    # 运行 shell 命令,直接提示

print(os.environ)       # 获取系统环境变量

5. json & pickle 模块

# -------------------------------------- json -----------------------------------------------
import json

with open("test.txt", "r+") as f:
    dic = {"name": "zhangsan", "age": 23, "phone": "13888888888"}
    data = json.dumps(dic)      # 序列化  json.dump(dic, f) 相当于 dumps 和 write 两步
    f.write(data)

with open("test.txt", "r+") as f:
    data = f.read()
    new_dic = json.loads(data)  # 反序列化 new_dic = json.load(f) 相当于read 和 loads 两步
    print(new_dic)

# -------------------------------------- pickle -----------------------------------------------
# pickle 使用方法和 json一样,但支持的数据类型更多
import pickle

with open("test.txt", "rb+") as f:
    dic = {"name": "zhangsan", "age": 23, "phone": "13888888888"}
    data = pickle.dumps(dic)
    f.write(data)

with open("test.txt", "rb+") as f:
    data = f.read()
    new_dic = pickle.loads(data)
    print(new_dic)

6. re 模块

import re

# findall 将匹配结果以列表形式返回,匹配不到则返回空列表
print(re.findall("\d", "34dfa345f"))    # \d 匹配一个数字
print(re.findall("\D", "34dfa345f"))    # \d 匹配一个非数字字符
print(re.findall("\w", "34dfa3_45f#"))    # \w 匹配包括下划线的任意单词字符
print(re.findall("^fa", "34dfa3_45f#"))    # ^ 匹配开头
print(re.findall("f#$", "34d#fa3_45f#"))    # $ 匹配结尾
print(re.findall(r"f{2,4}", "34d#fffffa3_45ff#"))    # {n,m} 匹配前一个字符n到m次,注意,{n,m}中间不能加空格
print(re.findall(r"f{2}", "34d#fffffa3_45ff#"))    # {n} 匹配前一个字符n次
print(re.findall(r"f{2,}", "34d#fffffa3_45ff#"))    # {n} 匹配前一个字符至少n次
print(re.findall(r"f*", "34d#fffffa3_45ff#"))    # * 匹配前一个字符0次或多次
print(re.findall(r"f+", "34d#fffffa3_45ff#"))    # + 匹配前一个字符1次或多次
print(re.findall(r"f?", "34d#fffffa3_45ff#"))    # ? 匹配前一个字符0次或1次
print(re.findall(r"f.", "34d#fffffa3_45f#"))    # . 匹配任意一个字符
print(re.findall("[a-z]", "34d#fffffa3_45f#"))    # [a-z] 匹配a到z中任意一个字符
print(re.findall("fa|f#", "34d#fffffa3_45f#"))    # x|y 匹配x或y
print(re.findall("(d#f)", "34d#fffffa3_45f#"))    # (pattern) 匹配pattern并获取这一匹配


# match从字符串开头开始,匹配则返回match object,不匹配返回 None
ret = re.match(pattern="4...z", string="45dfzdfa3gef4dgtzj")      # . 匹配任意字符
print(ret.group(0))
# search 匹配整个字符串,只要存在符合的则返回match object,不匹配返回 None
ret = re.search(pattern="4...z", string="dfa345dfzgef4dgtzj")     # . 匹配任意字符
print(ret.group(0))

7. logging 模块

import logging

# 设置参数
logging.basicConfig(
    level=logging.DEBUG,
    filename="logs/log.log",     # 设置log存储文件
    filemode="w",            # 默认以追加模式添加
    format="[%(lineno)d] %(asctime)s %(message)s"       # 设置日志显示格式
)

logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")
# -------------------------- logger  ----------------------------
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

fh = logging.FileHandler("logs/log.log")      # 向文件发送内容
ch = logging.StreamHandler()    # 向屏幕发送内容
fm = logging.Formatter("[%(lineno)d] %(asctime)s %(message)s")

fh.setFormatter(fm)     # 设置格式
ch.setFormatter(fm)

logger.addHandler(fh)    # 将相应的handler添加到logger对象中
logger.addHandler(ch)

logger.debug("debug message")
logger.info("info message")
logger.warning("warning message")
logger.error("error message")
logger.critical("critical message")

猜你喜欢

转载自www.cnblogs.com/sharef/p/9434976.html