一些模块

collections模块

''''''

# 具名元组
from collections import namedtuple

# point = namedtuple('坐标',['x','y'])  # 第一个参数传的是对后面元组的描述  第二个参数可以是可迭代对象
point = namedtuple('坐标', 'x y z')  # 第二个参数可以为字符串,但是每个字符都要用空格隔开
# point = namedtuple('坐标','xyz')  # 这里没有将字符串字符分隔开,只能穿一个值
# p = point(2,4)  # 给x,y进行传参,传入值2和4
p = point(1, 2, 3)  # 坐标(x=1, y=2, z=3)
# 可以通过p.x 取出出入的值




# 队列(先进先出)
import queue
res = queue.Queue()  # 生成队列对象 可以往里面添加值
res.put('cly')  # 往队列中传值
res.put('clysb')
res.put('clydsb')

# 从队列中取值
print(res.get())
print(res.get())
print(res.get())
print(res.get())  # 当队列中的值取完时,再取,程序会在原地等待,等到取到队列中的值 才会结束




# deque双端队列
from collections import deque

res = deque([1, 2, 3])
'''
# 双端队列需要掌握的方法
# append appendleft
# pop    popleft
# insert
'''
res.append('a')  # 在队列右边添加值
res.appendleft('c')  # 在队列左边添加值
r = res.pop()  # 从右边弹出值  在括号内添加值时,会报错
l = res.popleft()  # 从左边弹出值
# 双端队列有个很大的缺点,他能从中间添加值,这是一般队列没有的功能
res.insert(1, 'b')  # deque([1, 'b', 2, 3])  根据索引位置任意插值




# 有序字典
from collections import OrderedDict

# 在Python3中比较难看出有序字典,在python2中看的更加清晰
# order_1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# print(order_1)
order_d2 = OrderedDict()
order_d2['x'] = 1
order_d2['y'] = 2
order_d2['z'] = 3





# defaultdict(默认字典)
from collections import defaultdict
my_dict = defaultdict(list)  # 后续该字典中新建的key对应的value默认就是列表  每个键对应不同的列表
print(my_dict['aaa'])  # 为空列表
my_dict1 = defaultdict(int)
print(my_dict1['name'])  # 为数字0
my_dict2 = defaultdict(dict)
print(my_dict2['name'])  # 为空字典
my_dict3 = defaultdict(bool)
print(my_dict3['name'])  # 想都不用想 这为False
# 小练习
values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
dic1 = defaultdict(list)
for i in values:
    if i >= 66:
        dic1['k1'].append(i)
    else:
        dic1['k2'].append(i)
print(dic1)



# Counter
from collections import Counter
s = 'asdgdfgjsdljgfjsdfklsjdf'
i = Counter(s)  # 循环打印字符串,将每个字母与出现的次数以k:v形式存储
# print(i)  # Counter({'d': 5, 's': 4, 'f': 4, 'j': 4, 'g': 3, 'l': 2, 'a': 1, 'k': 1})

时间模块

# 共两个模块一个为time 另一个为datetime
# time
'''
三种表现形式
    1.时间戳
    2.格式化时间(就是我们平常看到的时间)
    3.结构化时间
'''
import time
# print(time.time())  # 距离1970年1月1日0点0时0分0秒的秒数

# 格式化时间
# print(time.strftime('%Y-%m-%d %H:%M:%S'))  # y需要大写  后面的小时分钟秒都需要大写
# print(time.strftime('%Y-%m-%d %X'))        # 小时分钟秒都可以用大写x来代替
print(time.strftime('%Y-%m',time.localtime()))
# 时间元组  time.localtime()









import datetime
# 获取本地时间
# 年月日
now_date = datetime.date.today()
print(now_date)  # 2019-07-18
# 年月日时分秒
now_time = datetime.datetime.today()
print(now_time)  # 2019-07-18 21:41:53.346249

random模块

# 共两个模块一个为time 另一个为datetime
# time
'''
三种表现形式
    1.时间戳
    2.格式化时间(就是我们平常看到的时间)
    3.结构化时间
'''
import time
# print(time.time())  # 距离1970年1月1日0点0时0分0秒的秒数

# 格式化时间
# print(time.strftime('%Y-%m-%d %H:%M:%S'))  # y需要大写  后面的小时分钟秒都需要大写
# print(time.strftime('%Y-%m-%d %X'))        # 小时分钟秒都可以用大写x来代替
print(time.strftime('%Y-%m',time.localtime()))
# 时间元组  time.localtime()









import datetime
# 获取本地时间
# 年月日
now_date = datetime.date.today()
print(now_date)  # 2019-07-18
# 年月日时分秒
now_time = datetime.datetime.today()
print(now_time)  # 2019-07-18 21:41:53.346249

os模块

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

BASE_DIR = os.path.dirname(__file__)
TANK_DIR = os.path.join(BASE_DIR, 'tank老师精选')  # 拼接绝对路径
tank_list = os.listdir(TANK_DIR)  # 查看文件夹中有什么文件 返回的是列表  文件夹中没有内容时,返回空list


# os.mkdir('tank')  # 创建文件夹


print(os.path.exists('111'))  # False  查兰文件夹是否存在
print(os.path.exists('tank'))  # True
print(os.path.exists(r'D:\py\day16\tank老师精选\tank-448.txt'))  # True  查看文件是否存在


print(os.path.isfile(r'D:\py\day16\tank老师精选\111'))  # 只能判断文件 不能判断文件夹  False
print(os.path.isfile(r'D:\py\day16\tank老师精选\tank-448.txt'))  # 只能判断文件 不能判断文件夹  True


# os.rmdir(r'D:\py\day16\tank老师精选\111')  # 只能删空文件夹


print(os.getcwd())  # 获取当前目录
os.chdir(r'D:\py\day16\tank老师精选')  # 切换当前目录
print(os.getcwd())  # D:\py\day16\tank老师精选 已经切换到tank老师精选目录


print(os.path.getsize(r'D:\py\day16\tank老师精选\tank-448.txt'))  # 获得文件大小  字节个数


# 练习题  让用户选择想看哪部
'''
while True:
    movie_tank = os.listdir('tank老师精选')
    for i,j in enumerate(movie_tank):
        print(i+1,j)
    choice = input('请选择你想看哪一部?').strip()
    if not choice.isdigit():
        print('输入有误')
        continue
    choice = int(choice)
    if choice in range(1,len(movie_tank)+1) :
        BASE_DIR = os.path.dirname(__file__)
        MOVIE_DIR = os.path.join(BASE_DIR, 'tank老师精选')
        look_file = os.path.join(MOVIE_DIR,movie_tank[choice-1])
        with open(look_file,'r',encoding='utf-8') as f:
            res = f.read()
            print(res)
    else:
        print('不在选择范围中')
'''

sys模块

import sys  # 与python打交道的模块
# sys.path.append()  将某个路径添加到环境变量中
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('用户不存在 无法执行当前文件')
subprocess 子进程
# 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'))

 

序列化模块
''''''
'''
序列化
    序列:字符串
    序列化:将其他数据转化为字符串
    反序列化:字符串转换为其他数据
'''
# json模块(********************)
# 所有语言都支持json
# 支持的数据类型很少  字符串 列表 字典 整型 元组(转成列表)  布尔值


# pickle模块(****)
# 只支持python
# python中所有数据类型都支持


import json

'''
dumps:序列化 将其他数据类型转换为json格式字符串
loads:反序列化  将json字符串转换为其他数据类型

dump  
load
'''

d = {'name': 'clydsb'}
res = json.dumps(d)  # {"name": "clydsb"}  json格式字符串为双引号
res1 = json.loads(res)
print(res1, type(res1))  # {'name': 'clydsb'} <class 'dict'>

with open('clysb,txt', 'w', encoding='utf-8') as f:
    json.dump(d, f)  # 将d转为字符串并写入文件

with open('clysb,txt', 'r', encoding='utf-8') as f:
    res = json.load(f)  # 反序列化只能读一条信息
    print(res)  # {'name': 'clydsb'}

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))

# pickle
import pickle

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

# 用pickle操作文件的时候 文件的打开模式必须是b模式
with open('cly', 'wb') as f:
    pickle.dump(d1, f)
with open('cly', 'rb') as f:
    res = pickle.load(f)
    print(res, type(res))

 

 
posted @ 2019-07-18 21:49  Nmdlao  阅读(175)  评论(0编辑  收藏  举报