总结十六

常用模块

一.collection模块

  在内置数据类型(dict、list、set、tuple)的基础上,collection模块还提供了几个额外的数据类型:counter、deque、defaultdict、namedtuple和OrderedDict等

  1.namedtuple:生成可以使用名字来访问元素内容的tuple

# 具名元组
# 想表示坐标点x为1,y为2的坐标
from collections import namedtuple
point = namedtuple('坐标',['x','y'])  # 第二个参数既可以传可迭代对象
point = namedtuple('坐标','x y')  # 也可以传字符串,但是字符串之间以空格隔开
p = point(1,2)  # 注意元素的个数必须跟namedtuple第二个参数里的值数量一致
print(p)
print(p.x)
print(p.y)

# 扑克牌
card = namedtuple('扑克牌','color number')
# card1 = namedtuple('扑克牌',['color','number'])
A = card('','A')
print(A)
print(A.color)
print(A.number)

# 记录信息
city = namedtuple('日本','name person size')
c = city('东京','J老师','L')
print(c)
print(c.name)
print(c.person)
print(c.size)

 

  2.deque:双端队列,可以快速的从另外一侧追加和退出对象

# 队列:先进先出(FIFO first in first out)
import queue
q = queue.Queue()   # 生成队列对象
q.put('first')  # 往队列中添加值
q.put('second')
q.put('third')

print(q.get())  # 朝队列要值
print(q.get())
print(q.get())
print(q.get())  # 如果队列中的值取完了,程序会在原地等待,直到从队列中拿到值才停止


# deque双端队列
from collections import deque
q = deque(['a','b','c'])
"""
append
appendleft

pop
popleft
"""
q.append(1)
q.appendleft(2)

"""
队列不应该支持任意位置插值
只能在首尾插值(不能插队)
"""
q.insert(0,'吼吼吼')  # 特殊点:双端队列可以根据索引在任意位置插值
print(q.pop())
print(q.popleft())
print(q.popleft())

 

  3.Counter:计数器,主要用来计数

from collections import Counter
s = 'abcdeabcdabcaba'
res = Counter(s)
print(res)
for i in res:
    print(i)

 

  4.OrderdDict:有序字典

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)])
order_d1 = OrderedDict()
order_d1['x'] = 1
order_d1['y'] = 2
order_d1['z'] = 3
print(order_d1)
for i in order_d1:
    print(i)
# print(order_d1)
# print(order_d)
order_d1 = dict()
order_d1['x'] = 1
order_d1['y'] = 2
order_d1['z'] = 3
print(order_d1)
for i in order_d1:
    print(i)

 

  5.defaultdict:带有默认值的字典

from collections import defaultdict
values = [11,22,33,44,55,66,77,88,99,90]
my_dict = defaultdict(list)  # 后续该字典中新建的key对应的value默认就是列表
print(my_dict['aaa'])
for value in values:
    if value > 66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict)

my_dict1 = defaultdict(int)
print(my_dict1['xxx'])
print(my_dict1['yyy'])

my_dict2 = defaultdict(bool)
print(my_dict2['kkk'])

my_dict3 = defaultdict(yuple)
print(my_dict3['mmm'])

 

二.时间模块

三种表现形式

  1.时间戳

  2.格式化时间(用来展示给人看的)

  3.结构化时间

import time
print(time.time())

print(time.strftime('%Y-%m-%d'))
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %X)   #  %X 等价于%H:%M:%S
print(time.strftime('%H:%M')
print(time.strftime('%Y/%m')

print(time.localtime())

print(time.localtime(time.time()))
res = time.localtime(time.time())
print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strrptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
# datetime
import(datetime.data.today())   # date>>>:年月日
print(datetime.datetime.today())  # datetime>>>:年月日 时分秒
res = datetime.data.today()
res1 = datetime.datetime.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday())  # 0-6表示星期  0 表示周一
print(res.isoweekday())  # 1-7表示星期  7就是周日
datetime

"""

(******)

日期对象 = 日期对象 +/- timedelta对象

timedelta对象 = 日期对象 +/- 日期对象

"""

import datetime
current_time = datetime.data.today()  # 日期对象
timetel_t = datatime.timedelta(days=7)  # timedelta对象
res1 = current_time=timetel_t  # 日期对象
print(current_time - timetel_t)
print(res1 - current_time)

 

三.random模块

随机模块

 

import random
print(random.randint(1,6))  # 随机取一个你提供的整数范围内的数字  包含首尾
print(random.random())   # 随机取0-1之间小数
print(random,choice([1,2,3,4,5,6]))  # 摇号 随机从列表中取一个元素
res = [1,2,3,4,5,6]
random.shuffle(res)  # 洗牌
print(res)


# 生成随机验证码
"""
大写字母 小写字母 数字
5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成纪委就生成几位
"""
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(4)  # 想要几位就在括号中输几位
print(res)

 

 

四.os模块

os模块是跟操作系统打交道的模块

os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息

os.system("bash command")  运行shell命令,直接显示
os.popen("bash command).read()  运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.path
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是绝对路径,返回True os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 os.path.getsize(path) 返回path的大小

os.sep        输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name       输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
 
 

五.sys模块

sys模块是跟python解释器打交道的模块

sys.argv          命令行参数list,第一个元素是程序本身路径

sys.version     获取Python解释器程序的版本信息

sys.path          返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform    返回操作系统平台名称

import sys
# sys.path.append()  # 将某个路径添加到系统的环境变量中
# print(sys.platform)
# print(sys.version)  # python解释器的版本

print(sys.argv)  # 命令行启动文件 可以做身份的验证
if len(sys.argv) <= 1:
    print('请输入用户名和密码')
else:
    username = sys.argv[1]
    password = sys.argv[2]
    if username == 'jason' and password == '123':
        print('欢迎使用')
        # 当前这个py文件逻辑代码
    else:
        print('用户不存在 无法执行当前文件')

 

六.序列化模块

序列化

  序列:字符串

  序列化:其他数据类型转换成字符串的过程

  反序列化:字符串转成其他数据类型

写入文件的数据必须是字符串

基于网络传输的数据必须是二进制

序列化的目的

  1.以某种存储形式使自定义对象持久化

  2.将对象从一个地方传递到另一个地方

  3.使程序更具维护性

 

json模块(******)

  所有的语言都支持json格式

  支持的数据类型很少  字符串 列表 字典 整型 元组(转成列表) 布尔值

pickle模块(****)

  只支持python

  python所有的数据类型支持

import json
"""
dumps:序列化 将其他数据类型转成json格式的字符串
loads:反序列化 将json格式的字符串转换成其他数据类型

dump load
"""
d = {"name":"jason"}
print(d)
res = json.dumps(d)  # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
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:
    json.dump(d,f)  # 装字符串并自动写入文件
    json.dump(d,f)  # 装字符串并自动写入文件

with open('userinfo','r',encoding='utf-8') as f:
    res1 = json.load(f)  # 不能够多次反序列化
    res2 = json.load(f)
    print(res1,type(res1))
    print(res2,type(res2))

with open('userinfo','w',encoding='utf-8') as f:
    json_str = json.dumps(d)
    json_str1 = json.dumps(d)
    f.write('%s\n'%json_str)
    f.write('%s\n'%json_str1)

with open('userinfo','r',encoding='utf-8') as f:
    for line in f:
        res = json.loads(line)
        print(res,type(res))
t = (1,2,3,4)
print(json.dumps(t))

d1 = {'name':'大马猴'}
print(json.dumps(d1,ensure_ascii=False))

pickle
import pickle
d = {'name':'jason'}
res = pickle.dumps(d)  # 将对象直接转成二进制
print(pickle.dumps(d))
res1 = pickle.loads(res)
print(res1,type(res1))

"""
用pickle操作文件的时候 文件的打开模式必须是b模式
"""
with open('userinfo_1','wb') as f:
    pickle.dump(d,f)

with open('userinfo_1','rb') as f:
    res = pickle.load(f)
    print(res,type(res))

 

七.subprocess模块

"""
1.用户通过网络连接上了你的这台电脑
2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
3.获取用户命令 里面subprocess执行该用户命令
4.将执行结果再基于网络发送给用户
这样就实现  用户远程操作你这台电脑的操作
"""
while True:
    cmd = input('cmd>>>:').strip()
    import subprocess
    obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    # print(obj)
    print('正确命令返回的结果stdout',obj.stdout.read().decode('gbk'))
    print('错误命令返回的提示信息stderr',obj.stderr.read().decode('gbk'))

 

转载于:https://www.cnblogs.com/TZZ1995/p/11210303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值