目錄
內(nèi)置模塊的介紹和使用
一、time模塊
在Python的三種時間表現(xiàn)形式:
- 時間戳:給電腦看的
- 自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()))
# 將時間對象轉(zhuǎn)為格式化時間
print(time.strftime('%Y-%m-%d %H:%M:%S', res))
# 將字符串格式的時間轉(zhuǎn)化為時間對象
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時區(qū):
北京時間
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中任意的整數(shù)
res = random.randint(1, 9)
print(res)
默認獲取0-1之間任意小數(shù)
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))
練習
隨機驗證碼
"""
需求:
大小寫字母、數(shù)字組合而成
組合5位數(shù)的隨機驗證碼
前置技術(shù):
chr() 可以將ASCII碼表中值轉(zhuǎn)換成對應的字符
"""
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)
# 隨機獲取一個數(shù)字
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 是與操作系統(tǒng)交互的模塊
獲取當前文件中的上一級目錄
DAY15_PATH = os.path.dirname(__file__)
print(DAY15_PATH)
E:/python_file/day 15
項目的根目錄,路徑相關(guān)的值都用 “常量”
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
創(chuàng)建文件夾
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('請輸入數(shù)字')
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解釋器的環(huán)境變量路徑
print(sys.path)
將當前項目添加到環(huán)境變量中
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_PATH)
獲取cmd終端的命令行 Python py文件 用戶名 密碼
print(sys.argv)
六、hashlib模塊
import hashlib
hashlib是一個加密模塊
? 內(nèi)置了很多算法
- MD5:不可解密的算法(2018年以前)
- 摘要算法
- 摘要是從某個內(nèi)容中獲取的加密字符串
- 摘要一樣,內(nèi)容就一定一樣:保證唯一性
- 密文密碼就是一個摘要
md5_obj = hashlib.md5()
print(type(md5_obj))
str1 = '1234'
# update中一定要傳入bytes類型數(shù)據(jù)
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類型數(shù)據(jù)
md5_obj.update(str1.encode('utf-8'))
# 創(chuàng)造鹽
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
|