標籤:注意 def linux reading mat gif 老王 date 生產者消費者
一、json模組
json(JavaScript Object Notation)JavaScript對象標記,JS對象標記法,JS的資料格式。
目前(今天2018年3月31日),從前端傳過來的資料,大部分是json格式,後端需要進行轉換。就是js和python進行互動。
(一).注意事項
(1).json對象必須是個字串
(2).json對象中,只要代表字串,必須要用雙引號。
(3).json對象中,不能出現單引號。同2
(二).幾個會常用的方法
(1).json.dumps(dict_object) 將python的字典對象,轉換為json對象
(2).json.loads(json_object) 將json對象,轉換成python的字典
(3).json.dump(dict_object, open("file_name.json","w")) 將字典轉換成json對象,並儲存為json檔案
(4).json.load(open("file_name.json")) 直接將檔案中的json對象,轉換成字典
二、os模組
目錄及檔案操作,與linux命令一樣的效果。
比如:
os.listdir(path) -> ls
os.makedirs("name") -> mkdir
(一).練習:
編寫一個函數,遍曆路徑下,所有的目錄和子目錄
"""編寫一個函數,遍曆路徑下,所有的目錄和子目錄"""import osdef list_all_file(file_path): paths = os.listdir(file_path) for each in paths: path_next = os.path.join(file_path, each) if os.path.isdir(path_next): list_all_file(path_next) else: print(os.path.join(file_path, path_next))list_all_file(r"D:\python_local")
View Code
三、datetime模組
具體用到,具體google it
注意點:
(一).strptime() 前後的格式要一樣。括弧中,前面的時間字串中是"-",那麼後面要格式化的字串也得是"-"。
(二).案例,輸出一個帶時區的日期時間格式:
import datetimedef utc_now(): dt = datetime.datetime.now() utc_time = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=datetime.timezone.utc) return utc_timeprint(utc_now())# 2018-07-06 16:59:50.256989+00:00
View Code
四、base64
是字元編碼,不是加密。
網頁上的圖片、影音都是二進位檔案。
現在圖片一般不會轉成base64了,一大串代碼,前端還不拿刀來砍死你 —.—
五、日誌模組
就是寫日記,記錄資訊。
補充練習:
"""OOP之生產者消費者模型用到一個模組 : 線程需求 : 吃包子有吃包子的人、有做包子的人我要讓吃包子和做包子同時進行,讓他們達到一個相對平衡"""import timeimport threadingclass PersonEatBaozi(threading.Thread): """ 吃包子的人 直接繼承threading.Thread """ def run(self): while 1: global count if con.acquire(): # 上鎖 if count < 100: con.wait() # 讓線程等待著 else: count -= 30 print("{}老王吃了30個包子,還剩{}個包子".format(self.name, str(count))) con.notify() # 通知其他線程,去搶線程 con.release() # 解鎖 time.sleep(1)class PersonMakeBaozi(threading.Thread): """做包子的人""" def run(self): while 1: global count if con.acquire(): if count > 1000: con.wait() else: count += 100 print("{}島歌做了100個包子,共有{}個包子".format(self.name, str(count))) con.notify() con.release() time.sleep(1)if __name__ == ‘__main__‘: count = 500 con = threading.Condition() # 開啟線程 for i in range(2): # 設定2個做包子的人 pm = PersonMakeBaozi() pm.start() # 啟動線程 for i in range(5): # 設定5個吃貨 pe = PersonEatBaozi() pe.start()View Code
Python 常用模組