在內置數據類型(dict、list、set、tuple)的基礎上,collection模塊還提供了幾個額外的數據類型:counter、deque、defaultdict、namedtuple和OrderedDict等python
1.namedtuple:生成可使用名字來訪問元素內容的tupleshell
# 具名元組 # 想表示座標點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:雙端隊列,能夠快速的從另一側追加和退出對象json
# 隊列:先進先出(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:計數器,主要用來計數bash
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:帶有默認值的字典app
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'])
三種表現形式dom
1.時間戳ide
2.格式化時間(用來展現給人看的)函數
3.結構化時間spa
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就是週日
"""
(******)
日期對象 = 日期對象 +/- 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)
隨機模塊
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.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模塊是跟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))
""" 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'))