常用模块:1.collection模块 2.time与datatime模块 3. random模块 4.os模块 5.sys模块 6.json模块 pickle模块 7.subprocess模块 #16

常用模块:

1.collection模块

collections 收藏,聚集

collections模块:
在内置数据类型(dict、list、set、tuple)的基础上,
collections模块还提供了几个额外的数据类型:
1.namedtuple(具名元组)
2.queue 先进先出(FIFO first in first out)
3.deque 双端队列
4.OrderedDict 在使用dict时key是无序的,在对dict做迭代时,我们无法确认key的顺序.如果要保持key的顺序,可用OrderedDict
5.Counter(计数器)
6.defaultdict 默认dict 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict
"""

  1 """
  2 collections 收藏,聚集
  3 
  4 collections模块:
  5       在内置数据类型(dict、list、set、tuple)的基础上,
  6       collections模块还提供了几个额外的数据类型:
  7       1.namedtuple(具名元组)
  8       2.queue 先进先出(FIFO first in first out)
  9       3.deque 双端队列
 10       4.OrderedDict 在使用dict时key是无序的,在对dict做迭代时,我们无法确认key的顺序.如果要保持key的顺序,可用OrderedDict
 11       5.Counter(计数器)
 12       6.defaultdict 默认dict 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict
 13 """
 14 
 15 """
 16 方法一:
 17 # namedtuple 具名元组: 具有名字的元组
 18 namedtuple 生成可以使用名字来访问元素内容的tuple
 19 格式:
 20 namedtuple('坐标',['x','y','z',])
 21 """
 22 # 案例1
 23 # 要求表示坐标点x点为1,y点为2
 24 # from collections import namedtuple
 25 # point = namedtuple('坐标',['x','y','z'])
 26 # print(point)  # <class '__main__.坐标'>
 27 # print(point(1,2,3))  # 坐标(x=1, y=2, z=3)
 28 # print(p.x)  # 1
 29 # print(p.y)  # 2
 30 # print(p.z)  # 5
 31 
 32 # 案例2
 33 # from collections import namedtuple
 34 # res = namedtuple('扑克牌',{'closer':'None','size':'None'})
 35 # # print(res(closer='♠',size='A'))
 36 # print(res('♠','A')) # 扑克牌(closer='♠', size='A')
 37 
 38 # # 案例三
 39 # from collections import namedtuple
 40 # ret = namedtuple('movie','movie_name person body')
 41 # print(ret('无间道', '刘建明', '双料卧底'))  # movie(movie_name='无间道', person='刘建明', body='双料卧底')
 42 """
 43 方法二
 44 queue 队列
 45 先进先出(FIFO first in first out)
 46 """
 47 # import queue
 48 # # 1.创建队列对象
 49 # res = queue.Queue()
 50 # # 2.往队列中添加值
 51 # res.put('1')
 52 # res.put('2')
 53 # res.put('3')
 54 # # 3.取值
 55 # print(res.get()) # 1
 56 # print(res.get()) # 2
 57 # print(res.get()) # 3
 58 # # ps:如果队列中的值传完了,程序会在原地等待,知道从队列中拿到值才停止
 59 # # 这里是阻塞状态,一直在等待着值进来~'''
 60 # print(res.get())
 61 # print(res.get())
 62 """
 63 方法三
 64 deque 双端队列
 65     四种使用方法:
 66         append 尾增
 67         appendleft  首增
 68         
 69         pop
 70         popleft
 71         ps:
 72         1.队列不应该支持任意位置插值,只能在首尾插值
 73         2.特殊点:双端队列可以根据索引在任意位置插值
 74     两种输出值方式:
 75         # 1# 值为对象
 76         res.pop()  # 尾删
 77         print(res)  # deque(['a', 'b', 'c'])  # 值为对象
 78         res.pop()  # 尾删
 79         print(res)  # deque(['a', 'b', 'c'])
 80         # 2 值为被操作的数值,如果对象中无,返回None
 81         print(res.append('5'))   # None  # 
 82         print(res.insert(1,'123'))  # None
 83         print(res.pop())  # 1 
 84 """
 85 # from collections import deque
 86 # #
 87 # res = deque()
 88 # res.append('llx')
 89 # print(res) # deque(['llx'])
 90 
 91 # 案例1
 92 # from collections import deque
 93 # # res = deque('abc')
 94 # res = deque(['a','b','c'])
 95 # # res = deque({'a':None,'b':None,'c':None})
 96 # # res = deque(('a','b','c'))
 97 # # 1.增
 98 # # 1.1.首尾增
 99 # res.append('1')  # 即尾部
100 # print(res)  # deque(['a', 'b', 'c', '1'])
101 # res.appendleft('left')
102 # print(res)  # deque(['left', 'a', 'b', 'c', '1'])   # 左边添加,即首部
103 # print(res.append('5'))   # None
104 # # 1.2 通过指定索引,在任意位置增
105 # res.insert(2,'嘿嘿')  # deque(['left', 'a', '嘿嘿', 'b', 'c', '1'])
106 # print(res)
107 # print(res.insert(1,'123'))  # None
108 # # 只能首尾删,不能指定删
109 # res.popleft() #首删
110 # print(res) # deque(['left', 'a', 'b', 'c', '1'])
111 # res.pop()  # 尾删
112 # print(res)  # deque(['a', 'b', 'c'])
113 # print(res.pop())  # 1
114 
115 """
116 方法四:
117 OrderedDict 有序字典
118 保持key的顺序,针对字典
119 使用dict时key是无序的,在做迭代的时候,我们无法确认key的顺序.如果要保持key的顺序,使用OrderedDict
120 
121 ps:OrderedDict 的key会按插入的顺序排列,而不是key本身
122 
123 """
124 # 案例
125 # from collections import OrderedDict
126 # p = OrderedDict({'a':None,'b':None,'c':None})
127 # print(p)  # OrderedDict([('a', None), ('b', None), ('c', None)])
128 # p1 = OrderedDict({'a':None,'c':None,'b':None})
129 # print(p1) # OrderedDict([('a', None), ('c', None), ('b', None)])
130 
131 # 案例2
132 # from collections import OrderedDict
133 # p = dict([('a', None), ('b', None), ('c', None)])
134 # print(p)
135 # p2 = OrderedDict([('a', None), ('b', None), ('c', None)])
136 # print(p2)
137 # OrderedDict([('a', None), ('b', None), ('c', None)])
138 # order_d1 = OrderedDict()
139 # order_d1['x'] = 1
140 # order_d1['y'] = 2
141 # order_d1['z'] = 3
142 # print(order_d1)
143 # for i in order_d1:
144 #     print(i)
145 # # print(order_d1)
146 # # print(order_d)
147 # order_d1 = dict()
148 # order_d1['x'] = 1
149 # order_d1['y'] = 2
150 # order_d1['z'] = 3
151 # print(order_d1)
152 # for i in order_d1:
153 #     print(i)
154 '''
155 # 注意  dict 字典在Python2下是无序的
156 >>> p = dict([('a', None), ('b', None), ('c'
157 , None)])
158 >>> p
159 {'a': None, 'c': None, 'b': None}
160 # 在OrderedDict 下是有序的(实际操作未成功,报错为找不到OrderedDict)
161 p2 = OrderedDict([('a', None), ('b', None), ('c', None)])
162 print(p2)
163 # OrderedDict([('a', None), ('b', None), ('c', None)])
164 '''
165 """
166 方法五:
167 defaultdict  默认字典
168     1.使用dict时,如果引用的Key不存在,就会抛出KeyError。
169     2.如果希望key不存在时,返回一个默认值,就可以用defaultdict
170 """
171 # l = {'a':None,'b':None,'c':None}
172 # print(l['d'])  # 报错:KeyError: 'd'
173 
174 # from collections import defaultdict
175 
176 # 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
177 # 两种解决方式
178 # 1.原生dict方法
179 # values = [11,22,33,44,55,66,77,88,99,90]
180 # # k1 = {}  # 大于66
181 # # k2 = {}  # 小于66
182 # my_k ={}
183 # for i in values:
184 #     if i > 66:
185 #         # if my_k['k1']:
186 #         # if my_k.has_key('k1'):
187 #         if my_k.get('k1'):
188 #             my_k['k1'].append(i)
189 #         else:
190 #             my_k['k1'] = i
191 #     else:
192 #         if my_k.get('k2'):
193 #         # if my_k.has_key('k1'):
194 #         # if my_k['k2']:
195 #             my_k['k2'].append(i)
196 #         else:
197 #             my_k['k2'] = i
198 # print(my_k())  # 无法运算 AttributeError: 'int' object has no attribute 'append'
199 # 2.defaultdict方法
200 # from collections import defaultdict
201 # values = [11, 22, 33,44,55,66,77,88,99,90]
202 # # 声明: # 后续该字典中新建的key对应的value默认就是列表
203 # my_dict = defaultdict(list)
204 # print(my_dict['aaa'])  # []
205 # for value in  values:
206 #     if value>66:
207 #         my_dict['k1'].append(value)
208 #     else:
209 #         my_dict['k2'].append(value)
210 # print(my_dict)  # defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})
211 
212 # 案例
213 # from collections import defaultdict
214 # # 声明 :之后传入参数,k 对应的volues为整型
215 # my_dict1 = defaultdict(int)
216 # print(my_dict1['xxx'])  # 0
217 # print(my_dict1['yyy'])  # 0
218 # ## 声明 :之后传入参数,k 对应的volues为bool类型
219 # my_dict2 = defaultdict(bool)
220 # print(my_dict2['kkk'])  # False
221 # ## 声明 :之后传入参数,k 对应的volues为元组
222 # my_dict3 = defaultdict(tuple)
223 # print(my_dict3['mmm'])  # ()
224 """
225 方法六:
226 counter 计数
227 作用:用来跟踪值出现的次数。
228 他是一个无序的容器类型,以字典键值对形式存储,其中元素作为k,计数作为v(v包括0和负数)
229 """
230 from collections import Counter
231 s = 'abcddddggfhghlkfdgkdfglkk;lhglj'
232 c = Counter(s)
233 # 打印元素 和计数
234 print(c)  # Counter({'d': 6, 'g': 6, 'l': 4, 'k': 4, 'f': 3, 'h': 3, 'a': 1, 'b': 1, 'c': 1, ';': 1, 'j': 1})
235 # 1.自己的方法 ***优选
236 # d = {}
237 # for i,j in c.items():
238 #     d[i] = j
239 # print(d)  # {'a': 1, 'b': 1, 'c': 1, 'd': 6, 'g': 6, 'f': 3, 'h': 3, 'l': 4, 'k': 4, ';': 1, 'j': 1}
240 # # 2.课堂内容方法
241 # for i in c:
242 #     print(i)
243 # # 先循环当前字符串 将每一个字符串都采用字典新建键值对的范式
244 # d = {}
245 # for i in s:
246 #     d[i] = 0
247 # print(d)  # {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'g': 0, 'f': 0, 'h': 0, 'l': 0, 'k': 0, ';': 0, 'j': 0}
collections模块

2.time与datatime模块

"""
时间模块
"""
"""
1.time
"""
"""
三种表现形式:
1.时间戳 time.time()
2.格式化时间(展示给人看的) time.strftime('%Y-%m-%d %H:%M:%S)
3.结构化时间 time.localtime() 即本地时间
"""

"""
2.datetime
"""
import datetime
# # 1.年月日时分秒
# print(datetime.datetime.today()) # 2019-07-18 11:39:41.026219
# # 2.年月日
# print(datetime.date.today()) # 2019-07-18
# # 3.年 月 日
# print(datetime.date.today().year) # 2019
# print(datetime.date.today().month) # 7
# print(datetime.date.today().day) # 18
# 4. 0-6 表示星期 , 0 表示周一
# 当天周几
# print(datetime.date.today().weekday()) # 3 代表周四
# # 1-7表示星期 7就是周日
# print(datetime.date.today().isoweekday()) # 4 周四
  1 """
  2 时间模块
  3 """
  4 """
  5 1.time
  6 """
  7 """
  8 三种表现形式:
  9 1.时间戳 time.time()
 10 2.格式化时间(展示给人看的) time.strftime('%Y-%m-%d %H:%M:%S)
 11 3.结构化时间 time.localtime() 即本地时间
 12 """
 13 import time
 14 # 1.时间戳
 15 # print(time.time())  # 1563420415.7168825
 16 # 2.格式化时间(展示给人看的)
 17 # print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 2019-07-18 11:26:55
 18 # 3.结构化时间(本地当前时间)
 19 # print(time.localtime())  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=11, tm_min=28, tm_sec=25, tm_wday=3, tm_yday=199, tm_isdst=0)
 20 
 21 
 22 # 其他方法:
 23 # 1.当地时间
 24 # print(time.localtime(time.time()))  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=20, tm_min=40, tm_sec=5, tm_wday=3, tm_yday=199, tm_isdst=0)
 25 ### 时间之间的相互装换
 26 # 时间戳转化为结构化时间
 27 # print(time.localtime(time.time()))  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=11, tm_min=26, tm_sec=55, tm_wday=3, tm_yday=199, tm_isdst=0)
 28 # 2.结构化时间-->时间戳
 29 # res = time.localtime(time.time())
 30 # print(time.mktime(res))
 31 # # 把时间戳转化为本地时间,再用
 32 # res = time.localtime(time.time())
 33 # print(time.mktime(res)) # 1563453330.0
 34 # print(time.time())  # 1563453358.1266172
 35 # 3.结构化时间-->字符串时间
 36 # time.strftime("格式定义","结构化时间")  结构化时间参数若不传,则显示当前时间如下
 37 # res = time.strftime("%Y-%m-%d %X")
 38 # '2019-07-18 20:46:01'
 39 # print(res)
 40 # ret = time.strftime("%Y-%m-%d",time.localtime(1500000000))
 41 # '2017-07-14'
 42 # print(ret)
 43 
 44 # 4.字符串时间-->结构化时间
 45 #time.strptime(时间字符串,字符串对应格式)
 46 # res = time.strptime("2017-03-16","%Y-%m-%d")
 47 # print(res)
 48 # # 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)
 49 # ret = time.strptime("07/24/2017","%m/%d/%Y")
 50 # print(ret)
 51 # 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)
 52 
 53 
 54 
 55 """
 56 2.datetime
 57 """
 58 import datetime
 59 # # 1.年月日时分秒
 60 # print(datetime.datetime.today())  # 2019-07-18 11:39:41.026219
 61 # # 2.年月日
 62 # print(datetime.date.today())  # 2019-07-18
 63 # # 3.年 月 日
 64 # print(datetime.date.today().year)  # 2019
 65 # print(datetime.date.today().month)  # 7
 66 # print(datetime.date.today().day)  # 18
 67 # 4.  0-6 表示星期 ,  0 表示周一
 68 # 当天周几
 69 # print(datetime.date.today().weekday()) # 3 代表周四
 70 # # 1-7表示星期 7就是周日
 71 # print(datetime.date.today().isoweekday()) # 4 周四
 72 
 73 """
 74 (******)
 75 日期对象 = 日期对象 +/- timedelta对象
 76 timedelta对象 = 日期对象 +/- 日期对象
 77 """
 78 # 日期对象 1
 79 # current_time1 = datetime.date.today()
 80 # print(current_time1)  # 2019-07-18
 81 #
 82 # # timetelta 对象  timetelta  时间标签  即:时间差值
 83 # timetel_time = datetime.timedelta(days=7)  # 7 days, 0:00:00
 84 # print(timetel_time)
 85 # # 日期对象 2
 86 # current_time2 = current_time1+timetel_time
 87 # print(current_time2)  # 2019-07-25
 88 #
 89 # # 日期对象 3
 90 # current_time3 = current_time1-timetel_time
 91 # print(current_time3)  # 2019-07-11
 92 #
 93 # print(current_time3-current_time2)  # -14 days, 0:00:00
 94 
 95 
 96 # 练习:
 97 # 距离今年过生日还需多久?
 98 import datetime
 99 # 日期对象---今日
100 res = datetime.datetime.today()  # 2019-07-18
101 # 日期对象---生日
102 ret = datetime.datetime(2019,8,13,21,35,41)
103 # 时间差值
104 print(ret - res)  # 25 days, 23:57:37.153281
105 
106 # UTC时间
107 # 当前时间
108 dt_today = datetime.datetime.today()
109 print(dt_today)  # 2019-07-18 21:42:29.317452
110 # 现在时间
111 dt_now = datetime.datetime.now()
112 print(dt_now)  # 2019-07-18 21:42:54.827337
113 # UTC现在时间
114 dt_utcnow = datetime.datetime.utcnow()  # 2019-07-18 21:44:23.995626
115 print(dt_now)
116 # 同一时间值相同
117 """
118 2019-07-18 21:44:41.882051
119 2019-07-18 21:44:41.882051
120 2019-07-18 21:44:41.882051
121 
122 """
时间模块

3.random模块

"""
random
"""
# import random
# # 1.随机取一个
# print(random.randint(1,6))
# # 2.随机取0-1之间的小数
# print(random.random())
# # 3.随机从列表中取数字
# print(random.choice([1,2,4,7,63,9]))
# # 4.洗牌
# print(random.shuffle([1,2,3,4,5,6,7,8,9,10])) # None
# res = [1,2,3,4,5,6,7,8,9,10]
# # 声明:洗牌
# # random.shuffle(res)
# # print(res) # [6, 9, 8, 4, 1, 2, 5, 7, 3, 10]
# print(random.shuffle(res)) # None

# print(random.choice([li.append(i) for i in range(1,34)]))

 1 """
 2 random
 3 """
 4 # import random
 5 # # 1.随机取一个
 6 # print(random.randint(1,6))
 7 # # 2.随机取0-1之间的小数
 8 # print(random.random())
 9 # # 3.随机从列表中取数字
10 # print(random.choice([1,2,4,7,63,9]))
11 # # 4.洗牌
12 # print(random.shuffle([1,2,3,4,5,6,7,8,9,10]))  # None
13 # res = [1,2,3,4,5,6,7,8,9,10]
14 # # 声明:洗牌
15 # # random.shuffle(res)
16 # # print(res)  # [6, 9, 8, 4, 1, 2, 5, 7, 3, 10]
17 # print(random.shuffle(res)) # None
18 
19 # print(random.choice([li.append(i) for i in range(1,34)]))
20 # 验证码
21 # # 1.自己
22 # import re
23 # def get_check():
24 #
25 #     res = re.findall('(?P<check_func>[0-9a-zA-z]{5})','123abcABCaaaaaa')
26 #     print(res)
27 #     print(random.choice(res))
28 #
29 # get_check()
30 
31 """
32 # 经典案例:
33 # 生成随机验证码
34 要求:5位数,大写字母,小写字母,数字
35 大写字母:[A-Z]
36 小写字母:[a-z]
37 数字:[0-9]
38 """
39 # 标准
40 import random
41 def my_code(n): # 外界传的验证码的位数
42     code = ''
43     for i in range(n):
44         # 大写字母
45         upper_str = chr(random.randint(65,90))
46         # 小写字母
47         lower_str = chr(random.randint(97,120))
48         # 数字
49         random_str = chr(random.randint(0,9))
50         # 在列表中选择随机数
51 
52         code += random.choice([upper_str,lower_str,random_str])
53     return code
54 
55 res = my_code(5)
56 print(res)
57 
58 import random
random随机数模块

4.os模块

"""
os模块:跟操作系统打交道的模块
1.什么是os
可以处理文件和目录,是Python系统和操作系统进行交互的一个接口

2.方法?
1.文件中的指定路径
os.path.dirname(__file__)
2.路径拼接
os.path.join('os.path.dirname(__file__)','文件名')
#3.打印当前文件夹下的目录
os.listdir('文件夹名称)

 1 """
 2 os模块:跟操作系统打交道的模块
 3 1.什么是os
 4 可以处理文件和目录,是Python系统和操作系统进行交互的一个接口
 5 
 6 2.方法?
 7 1.文件中的指定路径
 8 os.path.dirname(__file__)
 9 2.路径拼接
10 os.path.join('os.path.dirname(__file__)','文件名')
11 #3.打印当前文件夹下的目录
12 os.listdir('文件夹名称)
13 -
14 """
15 # 方法
16 import os
17 import os
18 BASE_DIR = os.path.dirname(os.path.dirname(__file__))
19 # print(BASE_DIR)
20 # E:/Python/项目/购物车面条版/day16.常用模块1.os 2.sys 3.time 4.json 5.pickle 6.random/4.os
21 MOVIE_DIR = os.path.join(BASE_DIR,'1')
22 # print(MOVIE_DIR)
23 # E:/Python/项目/购物车面条版/day16.常用模块1.os 2.sys 3.time 4.json 5.pickle 6.random/4.os老师们的作品
24 movie_list = os.listdir(MOVIE_DIR)
25 # print(movie_list) # []
26 
27 """
28 os的其他方法:
29 1.自动创建文件夹
30 os.path.mkdir('文件路径')
31 2.判断文件路径是否存在
32 os.path.exists(r'文件文件夹路径')
33 3.只能判断文件是否存在
34 os.path.isfile(r'文件路径')
35 4.只能删空文件夹
36 os.rmdir(r'文件路径')
37 5.获取当前工作目录,即当前python脚本工作的目录路径
38 os.getcwd()
39 6.切换当前所在的目录
40 os.chdir(r'文件路径')
41 7.获取文件大小--字节大小
42 os.path.getsize(r'文件路径')
43 """
44 
45 # 案例
46 # while True:
47 #     for i,j in enumerate(movie_list,1):
48 #         print(i,j)
49 #     choice = input('你想看谁的啊(今日热搜:tank老师)>>>:').strip()
50 #     if choice.isdigit():  # 判断用户输入的是否是纯数字
51 #         choice = int(choice)  # 传成int类型
52 #         if choice in range(1,len(movie_list)+1):  # 判断是否在列表元素个数范围内
53 #             # 获取用户想要看的文件名
54 #             target_file = movie_list[choice-1]
55 #             # 拼接文件绝对路径
56 #             target_path = os.path.join(MOVIE_DIR,target_file)
57 #             with open(target_path,'r',encoding='utf-8') as f:
58 #                 print(f.read())
os模块

5.sys模块

import sys
# 1.添加某个路径到环境变量
# sys.path.append()
# 3.操作系统平台名称
print(sys.platform)
# 4.python 解释器的版本
print(sys.version)
# 5.返回模块的搜索路径
print(sys.path)
# 2.命令启动文件,可以做身份证验证
print(sys.argv)

 1 import sys
 2 # 1.添加某个路径到环境变量
 3 # sys.path.append()
 4 # 3.操作系统平台名称
 5 print(sys.platform)
 6 # 4.python 解释器的版本
 7 print(sys.version)
 8 # 5.返回模块的搜索路径
 9 print(sys.path)
10 # 2.命令启动文件,可以做身份证验证
11 print(sys.argv)
12 # 在cmd,运行,后便可以直接输入到文件中
13 # 案例
14 # if len(sys.argv) <= 1:
15 #     print('请输入用户名和密码')
16 # else:
17 #     username = sys.argv[1]
18 #     password = sys.argv[2]
19 #     if username == 'jason' and password == '123':
20 #         print('欢迎使用')
21 #         # 当前这个py文件逻辑代码
22 #     else:
23 #         print('用户不存在 无法执行当前文件')
sys模块

6.序列化模块

 1 """
 2 序列化:
 3     序列:字符串
 4     序列化:其它数据类型转换成字符串的过程
 5 ps:
 6     1.写入文件的数据必须是字符串
 7     2.基于网络传输的的数据必须是二进制
 8 
 9 序列化:其他数据类型转换成字符串的过程
10 反序列化:字符串转换为其他字符串的过程
11 
12 序列化模块:
13 json模块*******所有的语言都支持json格式
14     支持的数据类型:很少(原因 :别的语言与Python可以对应的)
15     具体如下:str,list,dict,int,tuple(传给别人转为列表),bool
16 pickle模块***
17     只支持Python语言,
18     Python的所有类型都支持
19 
20 
21 """
22 d = {'name':'lllx'}
23 print(str(d))
序列化模块

json模块

 1 """
 2 json模块*******所有的语言都支持json格式
 3     支持的数据类型:很少(原因 :别的语言与Python可以对应的)
 4     具体如下:str,list,dict,int,tuple(传给别人转为列表),bool
 5 """
 6 import json
 7 """
 8 方法:
 9 dumps:序列化  将其他数据类型转成json格式的字符串
10 loads反序列化 将json格式的字符串转换成其它数据类型
11 
12 dump 序列化 并直接写进文件中 , 配合 with open()使用
13 load 反系列化 
14 """
15 import json
16 d = {"name":"jason"}
17 print(d)
18 res = json.dumps(d)  # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
19 print(res,type(res))
20 res1 = json.loads(res)
21 
22 print(res1,type(res1))
23 
24 #
25 # with open('userinfo','w',encoding='utf-8') as f:
26 #     json.dump(d,f)  # 装字符串并自动写入文件
27 #     json.dump(d,f)  # 装字符串并自动写入文件
28 
29 # with open('userinfo','r',encoding='utf-8') as f:
30 #     res1 = json.load(f)  # 不能够多次反序列化
31 #     res2 = json.load(f)
32 #     print(res1,type(res1))
33 #     print(res2,type(res2))
34 
35 
36 # with open('userinfo','w',encoding='utf-8') as f:
37 #     json_str = json.dumps(d)
38 #     json_str1 = json.dumps(d)
39 #     f.write('%s
'%json_str)
40 #     f.write('%s
'%json_str1)
41 
42 
43 # with open('userinfo','r',encoding='utf-8') as f:
44 #     for line in f:
45 #         res = json.loads(line)
46 #         print(res,type(res))
47 # t = (1,2,3,4)
48 # print(json.dumps(t))
49 
50 
51 # d1 = {'name':'朱志坚'}
52 # print(json.dumps(d1,ensure_ascii=False))
json模块

pickle模块

 1 """
 2 pickle模块***
 3     只支持Python语言,
 4     Python的所有类型都支持
 5     ps:用pickle操作文件的时候 文件的打开模式必须是b模式
 6 """
 7 # pickle
 8 # import pickle
 9 # d = {'name':'jason'}
10 # res = pickle.dumps(d)  # 将对象直接转成二进制
11 # print(pickle.dumps(d))
12 # res1 = pickle.loads(res)
13 # print(res1,type(res1))
14 
15 
16 # with open('userinfo_1','wb') as f:
17 #     pickle.dump(d,f)
18 
19 # with open('userinfo_1','rb') as f:
20 #     res = pickle.load(f)
21 #     print(res,type(res))
pickle模块

7.subprocess模块

 1 # subprocess
 2 """
 3 sub :子
 4 process:进程
 5 """
 6 
 7 
 8 """
 9 1.用户通过网络连接上了你的这台电脑
10 2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
11 3.获取用户命令 里面subprocess执行该用户命令
12 4.将执行结果再基于网络发送给用户
13 这样就实现  用户远程操作你这台电脑的操作
14 """
15 # while True:
16 #     cmd = input('cmd>>>:').strip()
17 #     import subprocess
18 #     obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
19 #     # print(obj)
20 #     print('正确命令返回的结果stdout',obj.stdout.read().decode('gbk'))
21 #     print('错误命令返回的提示信息stderr',obj.stderr.read().decode('gbk'))
subprocess模块

相关推荐