重要内置模块
目录
一.常用内置模块
1.collections模块
-
具名元组:namedtuple
from collections import namedtuple # 表示二维坐标系 point = namedtuple('点',['x', 'y']) # 生成点信息 p1 = point(1, 2) print(p1) # 点(x=1, y=2) print(p1.x) # 1 print(p1.y) # 2 card = namedtuple('扑克牌', ['num', 'color']) c1 = card('A', '♠') c2 = card('A', '♥') c3 = card('A', '♣') c4 = card('A', '♦') print(c1, c1.num, c1.color) print(c2, c2.num, c2.color) print(c3, c3.num, c3.color) print(c4, c4.num, c4.color)
-
队列
队列与堆栈
队列:先进先出
堆栈:先进后出
队列和堆栈都是一边只能进一边只能出
2.时间模块
-
时间的三种表现形式
1.时间戳
秒数
2.结构化时间
主要是给计算机看的 人看不适应
3.格式化时间
主要是给人看的
-
import time
print(time.time()) # 距离1970年01月01日 00:00:00所经过的时间(秒) print(time.localtime()) # 结构化时间 time.struct_time(tm_year=2022, tm_mon=10, tm_mday=19, tm_hour=16, tm_min=30, tm_sec=14, tm_wday=2, tm_yday=292, tm_isdst=0) print(time.strftime('%Y/%m/%d')) # 2022/10/19 '''其中/就是链接符,可以根据喜好自定义(- .)都可以 ''' print(time.strftime('%Y/%m/%d %H:%M:%S')) # 2022/10/19 16:40:30 print(time.strftime('%Y/%m/%d %X')) # 2022/10/19 16:40:30 %X就是%H:%M:%S time.sleep(数字) # 让程序原地阻塞指定的秒数
-
import datetime
import datetime print(datetime.datetime.now()) # 2022-10-19 16:49:26.261324 现在的时间 print(datetime.datetime.today()) # # 2022-10-19 16:49:26.261324 现在的时间 print(datetime.date.today()) # 2022-10-19 今天的日期 ''' datetime 年月日 时分秒 date 年月日 time 十分秒(后续会有此规律) ''' from datetime import date, datetime print(date.today()) # 2022-10-19 print(datetime.today()) # 2022-10-19 16:56:27.700645 print(datetime.utcnow()) # 2022-10-19 08:58:07.193017 utc指的是世界协调时间 import datetime c = datetime.datetime(2017, 5, 23, 12, 20) print('指定日期:', c) # 指定日期: 2017-05-23 12:20:00 from datetime import datetime d = datetime.strptime('2017/9/30', '%Y/%m/%d') print(d) # 2017-09-30 00:00:00 e=datetime.strptime('2017年9月30日星期六','%Y年%m月%d日星期六') print(e) f=datetime.strptime('2017年9月30日星期六8时42分24秒','%Y年%m月%d日星期六%H时%M分%S秒') print(f) import datetime ctime = datetime.date.today() print(ctime) # 2022-10-19 time_del = datetime.timedelta(days=3) print(ctime + time_del) # 2022-10-22 ctime = datetime.datetime.today() print(ctime) # 2022-10-19 17:16:06.855204 time_del = datetime.timedelta(minutes=20) print(ctime + time_del) # 2022-10-19 17:36:06.855204
索引(Index) | 属性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 60 |
6 | tm_wday(weekday) | 0 - 6(0表示周一) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为0 |
3.随机数模块
import random
print(random.random()) # 随机产生0到1之间的小数
print(random.randint(1, 6)) # 随机产生1到6之间的整数
print(random.randrange(1, 100, 2)) # 随机产生指定的整数 这里的2就是步长1 3 5 7
print(random.choice(['一等奖', '二等奖', '三等奖', '谢谢惠顾'])) # 随机抽取一个样本 '谢谢惠顾'
print(random.sample(['jason', 'kwvin', 'tony', 'oscar', 'jerry', 'tom', 2])) # 随机抽取指定样本数 ['tom', 'jason']
l1 = [2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A]
random.shuffle(l1) # 随机打乱数据集
print(l1)
面试题
'''产生图片验证码:每一位都可以是大写字母 小写字母 数字 4位'''
def get_code(n):
code = ''
for i in range(n):
# 1.先产生随机的大写字母 小写字母 数字
random_upper = chr(random.randint(65, 90))
random_lower = chr(random.randint(97, 122))
random_int = str(random.randint(0, 9))
# 2.随机三选一
temp = random.choice([random_upper, random_lower, random_int])
code += temp
return code
res = get_code(4) # 括号内传几 就会产生几位的验证码
print(res)
二.os模块
引入:
os模块主要与代码运行所在的操作系统打交道
1.创建目录(文件夹)
os.mkdir(r'd1') # 相对路径 在执行文件所在的路径下创建目录 可以创建单级目录
os.mkdir(r'd2\d22\d222') # 不可以创建多级目录
os.makdirs(r'd2\d22\d222') # 可以创建多级目录
os.makdirs(r'd3') # 也可以创建单级目录
2.删除目录(文件夹)
os.rmdir(r'di') # 可以删除单级目录
os.rmdir(r'd2\d22\d222') # 不可以一次性删除多级目录
os.removedirs(r'd2\d22') # 可以删除多级目录
os.removedires(r'd2\d22\d222\d2222') # 只能删除空的多级目录
os.rmdir(r'd3') # 只能删除空的单级目录
3.列举指定路径下内容名称
print(os.listdir())
print(os.listdir(r'D:\\'))
4.删除/重命名文件
os.rename(r'a.txt', r'aaa.txt')
os.remove(r'aaa.txt')
5.获取/切换当前工作目录
print(os.getcwd()) # D:\pythonProject03\day19
os.chdir('..') # 切换到上一级目录
print(os.getcwd()) # D:\pythonProject03
os.mkdir(r'hei')
6.动态获取项目根路径(重要)
print(os.path.abspath(__file__)) # 获取执行文件的绝对路径 D:/pythonProject03/day19/01 os模块.py
print(os.path.dirname(__file__)) # 获取执行文件所在的目录路径 D:/pythonProject03/day19
7.判断路径是否存在(文件、目录)
print(os.path.exists(r'01 os模块.py')) # 判断文件路劲是否存在 Ture
print(os.path.exists(r'D:\pythonProject03\day19')) # 判断目录是否存在 Ture
print(os.path.isfile(r'01 os模块.py')) # 判断路径是否是文件 Ture
print(os.path.isfile(r'pythonProject03\day19')) # 判断路径是否是文件 False
print(os.path.isdir(r'01 os模块.py')) # 判断文件是否为目录 False
print(os.path.isdir(r'D:\pythonProject03\day19')) # 判断文件是否为目录 Ture
8.路径拼接(重要)
s1 = r'D:\pythonProject03\day19'
s2 = r'01 os模块.py'
print(f'{s1}\{s2}')
"""
涉及到路径拼接一定不要自己做 因为不同的操作系统路径分隔符不一样
"""
print(os.path.join(s1, s2))
9.获取文件大小(字节)
print(os.path.getsize(r'a.txt'))
三.sys模块
import sys
print(sys.path) # 获取执行文件的sys.path
print(sys.getrecursionlimit) # 获取python解释器默认最大递归深度
sys.setrecursionlimit(2000) # 修改python解释器默认最大递归深度
print(sys.version) # 获取解释器的版本 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)]
print(sys.platform) # 平台信息 win32(了解即可)
res = sys.argv
if len(res) != 3:
print('执行命令缺少了用户名或密码')
else:
username = res[1]
password = res[2]
if username == 'jason' and password == '123':
print('jason您好 文件正常执行')
else:
print('您不是jason无权执行该文件')
四.json模块
json模块也称之为序列化模块 序列化可以打破语言限制实现不同编程语言之间数据交互
json格式数据的作用
json格式数据的形式:
字符串类型并且引号都是双引号
json相关操作
针对数据:
json.dumps()
json.loads()
针对文件
json.dump()
json.load()
五.json模块实战
用户登录注册功能
import os
import json
# 注册功能
# 1.获取执行文件所在的目录路径
base_dir = os.path.dirname(__file__) # E:/pythonProject3
# print(base_dir)
# 拼接出db目录路径
db_dir = os.path.join(base_dir, 'db') # E:/pythonProject3\db
# print(db_dir)
# 创建db目录
if not os.path.isdir(db_dir):
os.mkdir(db_dir)
# 4.获取用户数据
username = input('username>>>:').strip()
password = input('password>>>:').strip()
# 4.1判断用户名是否存在
print(os.listdir(db_dir)) # ['jason.json', 'kevin.json'] 方式一
# user_file_path = os.path.join(db_dir, f'{username}.json') # 方式二
# 5.构造用户字典
user_dict = {
'username': username,
'password': password,
'account': 18000, # 账户余额
'shop_car': [] # 购物车
}
# 6.拼接存储用户数据的文件路径
user_file_path = os.path.join(db_dir, f'{username}.json')
# 7.写入文件数据
with open(user_file_path, 'w', encoding='utf8') as f:
json.dump(user_dict, f)
# 登录功能
username = input('username>>>:').strip()
target_user_file_path = os.path.join(db_dir, f'{username}.json')
if not os.path.isfile(target_user_file_path):
print('用户名不存在')
else:
password = input('password>>>:').strip()
with open(target_user_file_path, 'r',encoding='utf8') as f:
real_user_dict = json.load(f)
if password == real_user_dict.get('password'):
print('登录成功')
else:
print('密码错误')