Copy
整形
浮点型
字符串
列表
字典
集合
元组
布尔值
collection模块#
Copy
from collections import namedtuple
point = namedtuple('坐标',['x','y'])
p = point(1,2)
print(p)
print(p.x)
print(p.y)
city = namedtuple('日本','name person size')
c = city('东京','R老师','L')
print(c)
print(c.name)
print(c.person)
print(c.size)
import queue
q = queue.Queue()
q.put('first')
q.put('second')
q.put('third')
print(q.get())
"""
append
appendleft
pop
popleft
"""
from collections import deque
q = deque(['a','b','c'])
q.append(1)
q.appendleft(2)
q.insert(0,'哈哈哈')
print(q.popleft())
"""
队列不应该支持任意位置插值
只能在首尾插值(不能插队)
"""
案例:将s中的每个单词作为key出现次数对应value 使用Counter模块实现
from collections import Counter
s = 'abcdeabcdabccaba'
res = Counter(s)
print(res)
normal_d = dict([('a',1),('b',2),('c',3)])
print(normal_d)
from collections import OrderedDict
order_d = OrderedDict([('a',1),('b',2),('c',3)])
print(order_d)
order_d1 = OrderedDict()
order_d1['x'] = 1
order_d1['y'] = 2
order_d1['z'] = 3
for i in order_d1:
print(i)
order_d2 = dict()
order_d2['x'] = 1
order_d2['y'] = 2
order_d2['z'] = 3
print(order_d2)
for i in order_d2:
print(i)
案例:列表值大于66那么字典的key为k1,反之字典的key为k2
from collections import defaultdict
values = [11,22,33,44,55,66,77,88,99]
my_dict = defaultdict(list)
for i in values:
if i > 66:
my_dict['k1'].append(i)
else:
my_dict['k2'].append(i)
print(my_dict)
时间模块#
Copy
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
"""
三种表现形式:
1. 时间戳(秒数)
2. 格式化时间(用来展示给人看的)
3. 结构化时间
"""
import time
print(time.time())
import time
print(time.strftime('%Y-%m-%d'))
import time
print(time.localtime())

Copy
>>>time.gmtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
>>>time.localtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
>>>time_tuple = time.localtime(1500000000)
>>>time.mktime(time_tuple)
1500000000.0
Copy
>>>time.strftime("%Y-%m-%d %X")
'2017-07-24 14:55:36'
>>>time.strftime("%Y-%m-%d",time.localtime(1500000000))
'2017-07-14'
>>>time.strptime("2017-03-16","%Y-%m-%d")
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1)
>>>time.strptime("07/24/2017","%m/%d/%Y")
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)

Copy
>>>time.asctime(time.localtime(1500000000))
'Fri Jul 14 10:40:00 2017'
>>>time.asctime()
'Mon Jul 24 15:18:33 2017'
>>>time.ctime()
'Mon Jul 24 15:19:07 2017'
>>>time.ctime(1500000000)
'Fri Jul 14 10:40:00 2017'
Copy
import time
true_time=time.mktime(time.strptime('2017-09-11 08:30:00','%Y-%m-%d %H:%M:%S'))
time_now=time.mktime(time.strptime('2017-09-12 11:00:00','%Y-%m-%d %H:%M:%S'))
dif_time=time_now-true_time
struct_time=time.gmtime(dif_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
struct_time.tm_mday-1,struct_time.tm_hour,
struct_time.tm_min,struct_time.tm_sec))
datetime模块#
Copy
import datetime
res = datetime.date(2019, 7, 15)
print(res)
now_date = datetime.date.today()
print(now_date)
now_time = datetime.datetime.today()
print(now_time)
print(now_time.year)
print(now_time.month)
print(now_time.day)
print(now_time.weekday())
print(now_time.isoweekday())
import datetime
tday = datetime.date.today()
tdelta = datetime.timedelta(days=7)
print('今天的日期:{}'.format(tday))
print('从今天向后推7天:{}'.format(tday + tdelta))
"""
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
验证:
"""
now_date1 = datetime.date.today()
lta = datetime.timedelta(days=6)
now_date2 = now_date1 + lta
print(type(now_date2))
lta2 = now_date1 - now_date2
print(type(lta2))
birthday = datetime.date(2019, 12, 21)
now_date = datetime.date.today()
days = birthday - now_date
print('生日:{}'.format(birthday))
print('今天的日期:{}'.format(tday))
print('距离生日还有{}天'.format(days))
import datetime
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_today)
print(dt_now)
print(dt_utcnow)
生成随机验证码#
Copy
"""
验证码构成:
大写字母 小写字母 数字
要求:
生成5位数的随机验证码
chr
random.choice
思路:
1. 先取出随机大写字母 小写字母 数字
2. for循环五次 在for循环上方定义空字符串名
3. 将int类型转换为str类型 进而实现后续五个字符拼接
4. 定义函数,用户随机取出任意位数验证码
ps:
A-Z 65-90
z-z 97-122
"""
def get_code(n):
code = ''
for i in range(n):
upper_str = chr(random.randint(65,90))
lower_str = chr(random.randint(97,122))
random_int = str(random.randint(0,9))
code += random.choice([upper_str,lower_str,random_int])
return code
res = get_code(5)
print(res)
后端代码统一转换成大写或者小写进行比对
os模块#
Copy
"""
os模块是和操作系统打交道的模块
sys模块是和python解释器打交道的模块
"""
import os
BASE_DIR = os.path.dirname(__file__)
MOVIE_DIR = os.path.join(BASE_DIR,'老师们的作品')
movie_list = os.listdir(MOVIE_DIR)
while True:
for i,j in enumerate(movie_list,1):
print(i,j)
choice = input('你想看谁的啊(今日热搜:tank老师)>>').strip()
if choice.isdigit():
choice = int(choice)
if choice in range(1,len(movie_list)+1):
target_file = movie_list[choice-1]
target_path = os.path.join(MOVIE_DIR,target_file)
with open(target_path,'r',encoding='utf-8') as f:
print(f.read())
os.mkdir('tank老师精选')
print(os.path.exists(r'F:\py_learn\老师们的作品'))
print(os.path.isfile(r'F:\py_learn\老师们的作品\明老师.txt'))
os.rmdir(r'F:\py_learn\老师们的作品')
print(os.getcwd())
print(os.chdir(r'F:\py_learn\老师们的作品'))
print(os.getcwd())
print(os.path.getsize(r'F:\py_learn\老师们的作品\明老师.txt'))
with open(r'F:\py_learn\老师们的作品\明老师.txt',encoding='utf-8') as f:
print(len(f.read()))
sys模块#
Copy
import sys
sys.path.append()
print(sys.version)
print(sys.argv)
username = sys.argv[1]
password = sys.argv[2]
if username == 'jason' and password == '123':
print('欢迎使用')
序列化模块#
Copy
"""
# 序列化
序列:字符串
序列化:其他数据类型转换成字符串的过程
写入文件的数据必须是字符串或者是二进制,因为只有字符串才能转换成二进制,所以写入文件的内容必须是字符串
基于网络传输的数据必须是二进制
序列化:其他数据类型转换成字符串的过程
反序列化:字符串转换成其他数据类型的过程
# 序列化模块:
json模块:
所有的语言都支持json格式 支持的数据类型很少
支持的数据类型:字符串 列表 字典 数字 元组(转成列表) 布尔值
pickle模块:
只支持python语言 python所有的数据类型都支持
"""
"""
json模块指南:
dumps:序列化 将其他类型的数据类型转换为字符串
loads:反序列化 将字符串转换为其他类型
dump:dump方法接收一个文件句柄,直接将其他类型换成json字符串写入文件
load:load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
# 使用记忆方式:
dumps和loads是直接对数据结构进行处理
dump和load是对文本进行处理
"""
import json
d = {'name':'jason'}
res = json.dumps(d)
print(res,type(res))
res1 = json.loads(res)
print(res1,type(res1))
d = {'name':'jason'}
with open('userinfo','w',encoding='utf-8') as f:
json.dump(d,f)
with open('userinfo','r',encoding='utf-8') as f:
res = json.load(f)
print(res,type(res))
with open('userinfo','w',encoding='utf-8') as f:
res = json.dumps(d)
res1 = json.dumps(d)
f.write('%s\n'%res)
f.write('%s\n'%res1)
with open('userinfo','r',encoding='utf-8') as f:
for i in f:
res = json.loads(i)
print(res,type(res))
t = (1,2,3,4)
res = json.dumps(t)
print(res,type(res))
a = {'name':'葬爱汤哥'}
print(json.dumps(a))
print(json.dumps(a,ensure_ascii=False))
"""
用pickle操作文件的时候 文件的打开模式必须是b模式
"""
import pickle
d = {'name':'jason'}
res = pickle.dumps(d)
print(res,type(res))
res1 = pickle.loads(res)
print(res1,type(res1))
with open('userinfo','wb') as f:
pickle.dump(d,f)
with open('userinfo','rb') as f:
res = pickle.load(f)
print(res,type(res))
subprocess模块#
Copy
"""
sub: 子
process: 进程
"""
import subprocess
obj = subprocess.Popen('xxxxx',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print('stdout',obj.stdout.read().decode('gbk'))
print('stderr',obj.stderr.read().decode('gbk'))
while True:
cmd = input('cmd>>>:').strip()
import subprocess
obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print('正确命令返回结果stdout',obj.stdout.read().decode('gbk'))
print('错误命令返回结果stderr',obj.stderr.read().decode('gbk'))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!