basicPython-5

os 模块

import os

# # 1 获取某一个文件夹下所有子文件以及子文件夹的名字
# res = os.listdir('.')
# print(res)

# # 2 读取某个"文件大小的属性"
# for i in res:
#     size = os.path.getsize(i)
#     print(size)

# 3 os.remove() 删除一个文件
# 4 os.rename(oldname,newname) 重命名文件/目录
# 5 os.system(r"dir C:\\a") 运行系统命令 -> dir[查看] 该路径下的文件有什么子文件夹/文件

# 6 print(os.environ) 获取系统环境变量,得到的是一个字典,根据字典特性,
# 可以将"某东西"通过-> environ[字符串]=字符串 <-直接加入系统环境变量中

# 7 os.path系列
# print(__file__)
# print(os.path.abspath(__file__))
# print(os.path.abspath('.'))

# res = os.path.split('/a/b/c/d.txt')
# print(res)

# print(os.path.dirname('/a/b/c/d.txt'))  # 获取其上一级名字
# print(os.path.basename('/a/b/c/d.txt'))  # 获取其最后的名字

# # 在python 3.5之后,推出了一个新的模块 pathlib
#
# from pathlib import Path
#
# # 魅力 x1
# p = Path(__file__)
# res = p.parent.parent
# print(res)
#
# # 魅力 x2
# res = Path('/a/b/c') / 'd/e.txt'
# print(res)

# 掌握:
print(os.path.isfile(r'C:\aaa'))  # 是否存在文件
print(os.path.dirname(r'c:\aaa\bbb'))
print(os.path.join('a,', 'C:' 'b', 'c', 'd', ))
print(os.path.normpath('/a/b/c/d/../..'))

sys 模块

import sys
import os

# 利用sys.argv获得的是解释器后面的参数 -> [run.py, 1, 2, 3]
# print(sys.argv)

# '''复制文件的工具(version 1.0)'''
#
# src_file = input('源文件路径>>>').strip()
# dst_file = input('目标文件路径>>>').strip()
#
# with open(r'%s' % src_file, mode='rb') as f1, \
#         open(r'%s' % dst_file, mode='wb') as f2:
#     while True:
#         res = f1.read(1024)
#         if not res:
#             break
#         f2.write(res)


'''复制文件的工具(version 2.0)---使用sys.argv功能'''

# 1 对输入的参数个数进行判断
length = len(sys.argv)
if length != 3:
    raise 'The number of parameters is incorrect'

# 2 进一步对参数进行识别
src_file = sys.argv[1]
dst_file = sys.argv[2]
# 2.1 两文件名相同
if src_file == dst_file:
    raise 'Duplicate file names'
# 2.2 原文件地址不存在
if not os.path.isfile(src_file):
    raise 'The file does not exist'
# 2.3 新文件地址已经存在
if os.path.isfile(dst_file):
    raise 'The file already exists'

# 3 复制文件
with open(r'%s' % src_file, mode='rb') as f1, \
        open(r'%s' % dst_file, mode='wb') as f2:
    while True:
        res = f1.read(1024)
        if not res:
            break
        f2.write(res)

random 模块

"""随机模块"""
import random

# 生成小数[无参数]
random.random()

# 生成整数
random.randint(-6, 6)  # [low, high]
random.randrange(-6, 6)  # [low, high)

# 生成实数[low, high]
random.uniform(-8, 8)

# 返回指定范围内的随机数[low, high)
"""
random.randrange(3, 30, 6)
它将生成 3 到 30 之间 "步长为>>>6" 的整数,如 3, 9, 15
"""
random.randrange(3, 20, 6)

# 随机取一个对象
list_1 = ['张大仙', 28, "贫穷", "乐观", "勇敢", ('可乐', '吃饭', '厕所')]
random.choice(list_1)

# 随机取多个对象(下例:取2个对象)
random.sample(list_1, 3)

# 随机打乱
"""
补充:用于将一个列表中的元素打乱顺序,值得注意的是使用这个方法不会生成新的列表,只是将原列表的次序打乱
"""
list_2 = [1, 3, 5, 7, 9]
random.shuffle(list_2)

"""
random模块练习
"""

"""生成n(n>=4)位密码(要求由数字、大写字母、小写字母和符号组成)"""


def generate_password(n=4):
    if n < 4:
        raise "The parameter must be greater than or equal to 4"

    list_3 = [[33, 47], [48, 57], [65, 90], [97, 122]]
    password = ""

    # 生成4位不同符号的密码(保底操作)
    for lt in list_3:
        num = random.randint(lt[0], lt[-1] + 1)
        password += chr(num)
    if n == 4:
        return password

    # 继续生成剩下的密码
    for i in range(1, n - 4 + 1):
        lt = random.choice(list_3)
        num = random.randint(lt[0], lt[-1] + 1)
        password += chr(num)
    # 将生成的密码打乱
    password = list(password)
    random.shuffle(password)
    password = "".join(password)
    return password


if __name__ == '__main__':
    print(generate_password(3))

time 模块

# # 第1部分:time模块
#
# import time
#
# # 1.时间戳(作用:用于时间间隔的计算)
# t1 = time.time()
# t2 = time.time()
# t = t2- t1
#
#
# # 2.格式化时间(作用:展示时间)
# # ---详细操作 (2023-05-22 16:58:51 Monday PM)
# print(time.strftime("%Y-%m-%d %H:%M:%S %A %p"))
#
# # ---默认简写 (05/22/23 17:01:04 Monday PM)
# print(time.strftime('%x %X %A %p'))
#
#
# # 3.结构化时间(作用:用于单独获取时间的某一部分)
# res = time.localtime()
# print(res)
# print(res.tm_year)
# print(res.tm_yday)


# # 第2部分:datetime模块
#
# import datetime
#
# # 1.快速展示现在的时间
# print(datetime.datetime.now())
#
# # 2.时间运算
# # ---以现在为准,算出7天前的具体时间
# res = datetime.datetime.now() + datetime.timedelta(days=-7)
# print(res)
#
# # ---以现在为准,算出4周前的具体时间
# res = datetime.datetime.now() + datetime.timedelta(weeks=-4)
# print(res)

# 第三部分:对于时间类型的模块需要掌握的是

# import time

# # 1 时间格式的转换
#
# # 1.1 struct_time -> 时间戳
# time1 = time.localtime()
# print(time1)
# print(time.mktime(time1))
#
# # 1.2 时间戳 -> struct_time
# time2 = time.time()
# print(time2)
# print(time.localtime(time2))
#
# # 1.3 世界标准时间(了解即可)
# print(time.gmtime(3333333))
#
# # 1.4 struct_time -> 格式化的字符串形式的时间
# time3 = time.localtime()
# res = time.strftime('%Y-%m-%d %H:%M:%S', time3)
# print(res)
#
# # 1.5 格式化的字符串形式的时间 -> struct_time
# res = time.strptime('1988-03-03 11:11:11', '%Y-%m-%d %H:%M:%S')
# print(res)
#
#
# # 2 总结:
# # 2.1 format string ---(strptime)---> struct_time ---(mktime)---> timestamp
# struct_time = time.strptime('1988-03-03 11:11:11', '%Y-%m-%d %H:%M:%S')
# timestamp = time.mktime(struct_time) + 7 * 86400  # 天的秒数为86400
# print(timestamp)
#
# # 2.2 format string <---(strftime)--- struct_time <---(localtime)--- timestamp
# res = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
# print(res)
#
# # 3 扩展了解
# import datetime
#
# # 3.1 时间戳 -> format string
# print(datetime.datetime.fromtimestamp(333333333))
#
# # 3.2 UTC【Coordinated Universal Time】时间不考虑任何地理位置或夏令时的差异,在全世界的各个时区中都是一致的
# print(datetime.datetime.utcnow())
#
# # 3.3
# print(time.asctime())

hash 模块

'''

1 什么是哈希hash?
    1.1 hash是一类算法,此算法接收传入的内容,通过运算得到一串的hash值(例如:md5、sha512、sha256)
    1.2 hash值的特点:
        1.2.1 只要传入的内容一样,得到的hash值必然相同
        1.2.2 不能由hash值反解成内容
        1.2.3 只要使用的hash算法不变,其hash长度是固定的


2 hash的用途
    2.1 用途1:特点2可以用于密码密文传输与验证
    2.2 用途2:特点1和3可以用于文件的完整性校验


3 如何使用

'''

# # 3 使用
# import hashlib
#
# m = hashlib.md5()
# m.update('hello'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# res1 = m.hexdigest()  # 'helloworld'的哈希值
# print(res1)
#
# b = hashlib.md5()
# b.update('helloworld'.encode('utf-8'))
# res2 = b.hexdigest()
# print(res2)
#
# print(res2 == res1)

''' 模拟撞库 '''

import hashlib

# 抓包获取了一个密码哈希值(md5)
password_hash = 'a820194546ecff7d3f909876bdc53b37'

# 从网上下载一个常用的密码库
password_list = ['123456', '778899', '1314520', 'qwq789123', 'cc56bb78']

# 哈希值准备
dic = {}
for i in password_list:
    # 算出当前密码的哈希值
    m = hashlib.md5()
    m.update(i.encode('utf-8'))
    hash_value = m.hexdigest()
    # 将信息以 -> 密码:哈希值 的键值对形式加入到字典中
    dic[i] = hash_value

# 开始撞库
for v in dic:
    if dic[v] == password_hash:
        print('撞库成功!密码原文>>>', v)
        break
else:
    print('撞库失败!')

''' 密码加盐 '''
# 假设用户的密码是 123456789
# 我们作为开发者,可以在客户端假设一个功能:
# 给用户设置的密码加上'王者归来'
# 规则如下:
# '王者'加在开头往后的第三个位置
# '归来'加在倒数第二个位置
# 加盐后的密码为:'12王者345678归来9'
# 再求对应的哈希值

re 模块

r'''左边的小r是为了防止转义"\"反斜杠


re模块 ~~~ 正则表达式


——————————————————————————————————————————
模式  ------------------  描述

\w  ------------------  匹配字母数字及下划线
\W  ------------------  上面取反
\s  ------------------  匹配任意空白字符,等价于[\t\n\r\f]
\S  ------------------  上门取反
\d  ------------------  匹配任意数字
\D  ------------------  上面取反
\A  ------------------  以什么开头 [了解]
\Z  ------------------  以什么结尾(不能用在有换行地方) [了解]
^什么   ------------------  以什么开头
什么$  ------------------ 以什么结尾
——————————————————————————————————————————
'''

import re

# 1 基本操作
# print(re.findall('\w', 'aAbc123_*()-='))
# print(re.findall('^love', 'love is my body, and I love it'))
# print(re.findall('love$', 'This is my love and The love is love'))

# 2 重复匹配

# 2.1 '.'匹配除了\n之外任意一个字符,指定re.DOTALL之后才能匹配换行
# print(re.findall('a.b', 'a1b a2b a b abbbb a\nb a\tb'))
# print(re.findall('a.b', 'a1b a2b a b abbbb a\nb a\tb', re.DOTALL))

# 2.2 '*'左边字符重复0次或以上,性格贪婪
# print(re.findall('ab*', 'a ab abb abbbbbb bbbbbbb'))

# 2.3 '+'左边字符重复1次或以上,性格贪婪
# print(re.findall('ab+', 'a ab abb abbbbb bbbbb '))

# 2.4 '?'左边字符重复0次或1次,性格贪婪
# print(re.findall('ab?', 'a ab abb bbbbb'))

# 2.5 '{n,m}'左边字符重复n次到m次,性格贪婪
# {0,} -> *
# {1,} -> +
# {0,1} -> ?
# {n} 单独一个n代表只出现n次

# print(re.findall('ab{2,5}','a ab abb abbb abbbb abbbbbbb bbbbbb'))

# 2.6 '[]'匹配指定字符一个
# print(re.findall('a[0-9]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[0-9a-zA-Z]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[^0-9a-zA-Z]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[-0-9\n]b', 'a-b a11111b a3b a4b a9b aXb a b a\nb'))

# 3 小练习

# 3.1 匹配出所有的数字
# print(re.findall('\d+\.?\d*', 'asdfasdf123as1.13dfa12adsf1asdf3'))

shutil 模块

import shutil

# 高级的文件、文件夹、压缩包处理模块

# 将文件内容拷贝到另一个文件中
shutil.copyfileobj(open('old.xml', 'r'), open('new.xml', 'w'))

# 拷贝文件和权限
shutil.copy('src', 'dst')

# 递归的删除文件(不可恢复)
shutil.rmtree('folder1')

# 递归的去移动文件,其实就是重命名
shutil.move('folder1', 'folder3')

logging 模块

字典方式配置日志

文件名: settings.py

# 将配置字典的format内容提取到最前面(方便修改格式)

standard_format = '[%(asctime)s] [%(threadName)s:%(thread)d] [task_id:%(name)s]]\
 [%(filename)s:%(lineno)s] [%(levelname)s]-> %(message)s'
simple_format = '[%(levelname)s] [%(asctime)s] [%(filename)s:%(lineno)d] [%(message)s]'

# 配置字典

LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'loggers': {
        'pen1': {
            'level': 'DEBUG',
            'handlers': ['console'],
            'propagate': False  # 默认为True(向更高level的logger传递)
        },
        'pen2': {
            'level': 'DEBUG',
            'handlers': ['default'],
            'propagate': False
        },
        '': {
            'level': 'DEBUG',
            'handlers': ['console', 'default'],
            'propagate': False

        },
    },
    'handlers': {
        # 输出终端模式
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        # 输出文件模式
        'default': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',  # 日志轮转
            'formatter': 'standard',
            'filename': 'test.log',  # 日志的文件命名
            'encoding': 'utf-8',  # 指定文件的编码格式
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 5
        }
    },
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        }
    },
    'filters': {}
}

文件名: start.py

# 使用字典的方式配置日志

import logging.config
from settings import LOGGING_DIC

# 加载配置字典
logging.config.dictConfig(LOGGING_DIC)

# 创建并调用logger
logger = logging.getLogger('提现功能')

# 发出信息
logger.debug('这是一条debug')
logger.info('这是一条info')

logger.warning('这是一条warning')
logger.error('这是一条error')
logger.critical('这是一条critical')

编程式使用日志

文件名: log1

import logging

# # 输出程序运行的信息给维护人员看
# logging.debug('This is debug log')
# logging.info('This is info log')
# logging.warning('This is warning log')
# logging.error('This is error log')
# logging.critical('This is critical log')


# # 默认的日志输出级别为warning
# # 可使用baseConfig()来指定日志输出级别
# logging.basicConfig(level=logging.DEBUG)
# logging.debug('This is debug log')
# logging.info('This is info log')
# logging.warning('This is warning log')
# logging.error('This is error log')
# logging.critical('This is critical log')

文件名: log2

import logging

# 向文件输出日志 (文件的操作->默认是'a'模式, 可使用filemode='w'等等自行修改)
logging.basicConfig(filename='demo.log', filemode='a', level=logging.DEBUG)
logging.debug('This is debug log')
logging.info('This is info log')
logging.warning('This is warning log')
logging.error('This is error log')
logging.critical('This is critical log')

文件名: log3

import logging

# "绝对自定义"输出信息:format -> message
logging.basicConfig(format='%(message)s', level=logging.DEBUG)

# 日志中的message部分:
name = 'peter'
age = '18'
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))

文件名: log4

import logging

# 输出格式和添加一些公共信息
logging.basicConfig(format='%(asctime)s---%(levelname)s---%(filename)s---%(lineno)s---%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',  # 对上面的时间格式不满意,自定义后,再去覆盖原来提供给我们的时间格式
                    level=logging.DEBUG)

# 日志中的message部分:
name = 'peter'
age = '18'
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))
logging.warning('姓名:%s, 年龄:%s, 充值失败' % (name, age))

文件名: log5

# 编程的方式来写一下高级的写法

'''
# logging的高级应用
# 它提供给我们了四个类

Loggers: 记录器,提供应用程序代码能直接使用的接口
Handlers: 处理器,将记录器产生的日志发送到目的地
Filters: 过滤器,提供更好的粒度控制,决定哪些日志会被输出
Formatters: 格式化器,设置日志内容的组成结构和消息字段
'''

import logging

# 记录器Logger
logger1 = logging.getLogger('applog')
logger1.setLevel(logging.DEBUG)

# 处理器handler
# --处理器1
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
# --处理器2
fileHandler = logging.FileHandler(filename='addDemo.log')
fileHandler.setLevel(logging.CRITICAL)

# 格式器formatter
fmt = logging.Formatter('%(asctime)s|%(levelname)-8s|%(filename)10s:%(lineno)4s|%(message)s')

# 给处理器设置格式
consoleHandler.setFormatter(fmt)
fileHandler.setFormatter(fmt)

# 给记录器设置处理器
logger1.addHandler(consoleHandler)
logger1.addHandler(fileHandler)

# 定义一个过滤器
flt = logging.Filter('cn.cccb')

# 关联过滤器
# logger1.addFilter(flt)
fileHandler.addFilter(flt)
# consoleHandler.addFilter(flt)

# 调用部分之发出日志信息
logger1.debug('This is debug')
logger1.info('This is info')
logger1.warning('This is warning')
logger1.error('This is error')
logger1.critical('This is critical')

配置文件式使用日志

文件名: loggg.conf

[loggers]
keys=root,applog

[handlers]
keys=fileHandler,consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_applog]
level=DEBUG
handlers=fileHandler,consoleHandler
qualname=applog
propagate=0

[handler_consoleHandler]
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatters=simpleFormatter

[handler_fileHandler]
class=handlers.TimedRotatingFileHandler
args=('applog.log','midnight',1,0)
level=DEBUG
formatters=simpleFormatter

[formatter_simpleFormatter]
format=%(asctime)s|%(levelname)8s|%(filename)s[:%(lineno)d]|%(message)s
datefmt=%Y-%m-%d %H:%M:%S

文件名: log11.py

# 配置文件的方式来处理日志

import logging
import logging.config

# 加载配置文件
logging.config.fileConfig('loggg.conf')

# 获取两个logger并使用即可
rootLogger = logging.getLogger()
rootLogger.debug('This is a root Logger, debug')

logger = logging.getLogger('applog')
logger.debug('This is applog, debug')

# 知识补充(绝对捕获异常):
a = 'abc'
try:
    int(a)
except Exception as e:
    # logger.error(e)
    logger.exception(e)

subprocess 模块

''' 执行系统命令的模块 '''
import subprocess

# 创建一个对象,如果命令执行错误,结果走错误管道,反之
obj = subprocess.Popen('dir D:', shell=True,  # 查看D盘下的内容, shell=True相当于调用了cmd
                       stdout=subprocess.PIPE,  # 正确输出=管道
                       stderr=subprocess.PIPE,  # 错误输出=管道
                       )

# 打印对象
print(obj)

# # 查看两个管道的结果
# print(obj.stdout.read())  # 正确输出的那条管道
# print(obj.stderr.read())  # 错误输出的那条管道

# 查看两个管道的结果
print(obj.stdout.read().decode('gbk'))  # 正确输出的那条管道(跟着系统的编码进行信息解码)
print(obj.stderr.read().decode('gbk'))  # 错误输出的那条管道(跟着系统的编码进行信息解码)

configparser 模块

'''
对配置文件进行操作的模块(configparser)
'''

import configparser

config = configparser.ConfigParser()
config.read('test.ini')  # 获取配置文件的信息

# 获取sections
# print(config.sections())

# 获取某一sections下的所有options
# print(config.options('sections1'))

# 获取items
# print(config.items('sections1'))

# 获取具体的某个参数
# res = config.get('sections1', 'user')
# print(res, type(res))

# res = config.getint('sections1', 'age')
# print(res, type(res))

# res = config.getboolean('sections1', 'is_admin')
# print(res, type(res))

你可能感兴趣的:(Python基础,python)