目录
内置模块的介绍和使用
一、time模块
在Python的三种时间表现形式:
- 时间戳:给电脑看的
- 自1970-01-01 00:00:00 到当前时间,按秒计算,计算了多少秒
- 格式化时间(Format String):给人看的
- 格式化时间对象(struct_time):
- 返回的是一个元组,元组中有9个值:
- 分别代表:年、月、日、时、分、秒、一周中第几天、一年中的第几天、夏令时
import time
获取时间戳 计算时间时使用
print(time.time())
- 获取格式化时间,拼接用户时间格式并保存时使用
time.strftime('%Y-%m-%d %H:%M:%S') 获取年月日时分秒
- %Y 年
%m 月
%d 日
%H 时
%M 分
%S 秒
获取当前时间的格式化时间
获取实践对象
res = time.localtime()
# 获取当前时间的格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 将时间对象转为格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', res))
# 将字符串格式的时间转化为时间对象
res = time.strptime('2019-01-01', '%Y-%m-%d')
print(res)
2019-11-16 15:23:17
2019-11-16 15:23:17
time.struct_time(tm_year=2019, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=1, tm_isdst=-1)
二、datetime 模块
import datetime
# 获取当前年月日
print(datetime.date.today())
2019-11-16
# 获取当年年月日时分秒
print(datetime.datetime.today())
2019-11-16 15:26:37.224224
time_obj = datetime.datetime.today()
print(time_obj.year)
print(time_obj.month)
print(time_obj.day)
2019
11
16
# 从索引0开始计算周一
# UTC
print(time_obj.weekday()) # 0-6
# ISO
print(time_obj.isoweekday()) # 1-7
UTC时区:
北京时间
print(datetime.datetime.now())
格林威治
print(datetime.datetime.utcnow())
日期/时间的计算
日期时间 = 日期时间“ ” or “-” 时间对象
时间对象 = 日期时间“ ” or “-” 日期时间
# 日期时间
current_time = datetime.datetime.now()
print(current_time)
# 获取7天时间
time_obj = datetime.timedelta(days=7)
print(time_obj)
# 获取当前时间 7天后的时间
later_time = current_time time_obj
print(later_time)
time_new_obj = later_time - time_obj
print(time_new_obj)
三、random模块
import random
随机获取1-9中任意的整数
res = random.randint(1, 9)
print(res)
默认获取0-1之间任意小数
res1 = random.random()
print(res1)
将可迭代对象中的值进行打乱顺序(洗牌)
l1 = [5, 4, 9, 8, 6, 7, 3, 1, 2, 0]
random.shuffle(l1)
print(l1)
随机获取可迭代对象中的某一个值
l1 = [5, 4, 9, 8, 6, 7, 3, 1, 2, 0]
print(random.choice(l1))
练习
随机验证码
"""
需求:
大小写字母、数字组合而成
组合5位数的随机验证码
前置技术:
chr() 可以将ASCII码表中值转换成对应的字符
"""
def get_code(n):
code = ''
for line in range(n):
# 随机获取一个小写字母
res1 = random.randint(97, 122)
lower_str = chr(res1)
# 随机获取一个大写字母
res2 = random.randint(65, 90)
upper_str = chr(res2)
# 随机获取一个数字
number = str(random.randint(0, 9))
code_list = [lower_str, upper_str, number]
random_code = random.choice(code_list)
code = random_code
return code
code = get_code(4)
print(code)
四、OS模块
import os
os 是与操作系统交互的模块
获取当前文件中的上一级目录
DAY15_PATH = os.path.dirname(__file__)
print(DAY15_PATH)
E:/python_file/day 15
项目的根目录,路径相关的值都用 “常量”
BASE_PATH = os.path.dirname(DAY15_PATH)
print(BASE_PATH)
E:/python_file
路径的拼接: 拼接文件 “绝对路径”
TEST_PATH = os.path.join(DAY15_PATH,'合集')
print(TEST_PATH)
E:/python_file/day 15\合集
判断“文件/文件夹”是否存在:若文件存在返回True,若不存在返回False
print(os.path.exists(TEST_PATH))
print(os.path.exists(DAY15_PATH))
False
True
判断“文件夹”是否存在
print(os.path.isdir(TEST_PATH))
print(os.path.isdir(DAY15_PATH))
False
True
判断“文件”是否存在
print(os.path.isfile(TEST_PATH))
print(os.path.isfile(DAY15_PATH))
False
True
创建文件夹
DIR_PATH = os.path.join(DAY15_PATH,'合集')
os.mkdir(DIR_PATH)
删除文件夹
os.rmdir(DIR_PATH)
获取某个文件夹中所有文件的名字
# 获取某个文件夹下所有文件的名字,然后装进一个列表中
list1 = os.listdir('E:\python_file\day 15')
print(list1)
['01 time模块.py', '02 datetime模块.py', '03 random模块.py', '04 os模块.py', '05 sys模块.py', '06 hashlib模块.py', 'sys_test.py', 'test(day 15).py', '课堂笔记']
enumerate(可迭代对象) ---> 得到一个对象,对象有一个个的元组(索引, 元素)
res = enumerate(list1)
print(list(res))
[(0, '01 time模块.py'), (1, '02 datetime模块.py'), (2, '03 random模块.py'), (3, '04 os模块.py'), (4, '05 sys模块.py'), (5, '06 hashlib模块.py'), (6, 'sys_test.py'), (7, 'test(day 15).py'), (8, '课堂笔记')]
让用户选择文件
list1 = os.listdir('E:\python_file\day 15')
res = enumerate(list1)
print(list(res))
# 让用户选择文件
while True:
for index, file in enumerate(list1):
print(f'编号{index} 文件名{file}')
choice = input('请选择需要的文件编号:').strip()
if not choice.isdigit():
print('请输入数字')
continue
choice = int(choice)
if choice not in range(len(list1)):
print('编号范围出错')
continue
file_name = list1[choice]
list1_path = os.path.join('E:\python_file\day 15', file_name)
print(list1_path)
with open(list1_path, 'r', encoding='utf-8')as f:
print(f.read())
五、sys模块
import sys
获取当前的Python解释器的环境变量路径
print(sys.path)
将当前项目添加到环境变量中
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_PATH)
获取cmd终端的命令行 Python py文件 用户名 密码
print(sys.argv)
六、hashlib模块
import hashlib
hashlib是一个加密模块
内置了很多算法
- MD5:不可解密的算法(2018年以前)
- 摘要算法
- 摘要是从某个内容中获取的加密字符串
- 摘要一样,内容就一定一样:保证唯一性
- 密文密码就是一个摘要
md5_obj = hashlib.md5()
print(type(md5_obj))
str1 = '1234'
# update中一定要传入bytes类型数据
md5_obj.update(str1.encode('utf-8'))
# 得到一个加密后的字符串
res = md5_obj.hexdigest()
print(res)
<class '_hashlib.HASH'>
81dc9bdb52d04dc20036dbd8313ed055
以上操作撞库有可能会破解真实密码
防止撞库问题:加盐
def pwd_md5(pwd):
md5_obj = hashlib.md5()
str1 = pwd
# update 中一定要传入bytes类型数据
md5_obj.update(str1.encode('utf-8'))
# 创造盐
sal = '我套你猴子'
# 加盐
md5_obj.update(sal.encode('utf-8'))
# 得到一个加密后的字符串
res = md5_obj.hexdigest()
return res
res = pwd_md5('1234')
user_str1 = f'yang:1234'
user_str2 = f'yang:{res}'
with open('user_info.txt', 'w', encoding='utf-8')as f:
f.write(user_str2)
模拟用户登录功能
# 获取文件中的用户名密码
with open('user_info.txt', 'r', encoding='utf-8')as f:
user_str = f.read()
file_user, file_pwd = user_str.split(':')
# 用户输入用户名和密码
username = input('请输入用户名:').strip()
password = input('请输入密码:').strip()
if username == file_user and file_pwd == pwd_md5(password):
print('登录成功')
else:
print('登录失败')
来源:https://www./content-4-566601.html
|