import random(模塊)node
import random 取隨機小數 : 數學計算 print(random.random()) # 取0-1之間的小數 (大於0小於1之間的數) print(random.uniform(1,2)) # 取1-2之間的小數 (大於1小於2之間的數) 取隨機整數 : 彩票 抽獎 print(random.randint(1,2)) # [1,2] print(random.randrange(1,2)) # [1,2) print(random.randrange(1,200,2)) # [1,2)
隨機整數
>>> random.randint(1,5) # 大於等於1且小於等於5之間的整數 >>> random.randrange(1,10,2) # 大於等於1且小於10之間的奇數
從一個列表中隨機抽取值 : 抽獎 l = ['a','b',(1,2),123] print(random.choice(l)) print(random.sample(l,2))
隨機選擇一個返回>>> random.choice([1,'23',[4,5]]) # #1或者23或者[4,5]
#隨機選擇多個返回,返回的個數爲函數的第二個參數 >>> random.sample([1,'23',[4,5]],2) # #列表元素任意2個組合
[[4, 5], '23']
打亂一個列表的順序,在原列表的基礎上直接進行修改,節省空間 洗牌 random.shuffle(l) print(l)
打亂列表順序
>>> item=[1,3,5,7,9] >>> random.shuffle(item) # 打亂次序 >>> item [5, 1, 3, 7, 9] >>> random.shuffle(item) #每一次順序不同 >>> item [5, 9, 7, 1, 3]
4位數字驗證碼(隨機數字)python
# s = '' # for i in range(4): # num = random.randint(0,9) # s += str(num) # print(s)
6位數字驗證碼(隨機數字)shell
# s = '' # for i in range(6): # num = random.randint(0,9) # s += str(num) # print(s)
函數版的6位4位驗證碼(隨機數字)bash
def code(n=6): s = '' for i in range(n): num = random.randint(0,9) s += str(num) return s print(code(4)) print(code())
6位數字+字母驗證碼(隨機數字)app
一個位置上 出現的是數字仍是字母 是隨機數字 隨機字母dom
s = '' for i in range(6): # 生成隨機的大寫字母,小寫字母,數字各一個 num = str(random.randint(0,9)) alpha_upper = chr(random.randint(65,90)) alpha_lower = chr(random.randint(97,122)) res = random.choice([num,alpha_upper,alpha_lower]) s += res print(s)
函數版4位6位 數字字母混合驗證碼(隨機數字字母)ide
def code(n = 6): s = '' for i in range(n): # 生成隨機的大寫字母,小寫字母,數字各一個 num = str(random.randint(0,9)) alpha_upper = chr(random.randint(65,90)) alpha_lower = chr(random.randint(97,122)) res = random.choice([num,alpha_upper,alpha_lower]) s += res return s print(code(4)) print(code())
函數版4位 6位數字字母大小寫混合驗證碼(隨機數字字母)函數
def code(n = 6,alpha = True): s = '' for i in range(n): # 生成隨機的大寫字母,小寫字母,數字各一個 if alpha: num = str(random.randint(0,9)) alpha_upper = chr(random.randint(65,90)) alpha_lower = chr(random.randint(97,122)) res = random.choice([num,alpha_upper,alpha_lower]) s += res else: num = random.randint(0, 9) s += str(num) return s print(code(4)) print(code())
函數版4位 6位 數字驗證碼(隨機數字)ui
def code(n = 6,alpha = True): s = '' for i in range(n): num = str(random.randint(0,9)) if alpha: alpha_upper = chr(random.randint(65,90)) alpha_lower = chr(random.randint(97,122)) num = random.choice([num,alpha_upper,alpha_lower]) s += num return s print(code(4,False)) print(code(alpha=False))
時間模塊 import timespa
和時間有關係的咱們就要用到時間模塊. 在使用模塊以前, 先導入這個模塊
#經常使用方法 1.time.sleep(secs) (線程)推遲指定的時間運行。單位爲秒。 2.time.time() 獲取當前時間戳
表示時間的三種方式
在python中, 一般有三種方式來表示時間:時間戳 , 元祖(struct_time) , 格式化的時間字符串:
(1)時間戳(timestamp) : 一般來講 , 時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量.咱們運行"type(time.time())",返回的是float類型.
(2)格式化的時間字符串(Format String): '1999-12-06'
1 %y 兩位數的年份表示(00-99) 2 %Y 四位數的年份表示(000-9999) 3 %m 月份(01-12) 4 %d 月內中的一天(0-31) 5 %H 24小時制小時數(0-23) 6 %I 12小時制小時數(01-12) 7 %M 分鐘數(00=59) 8 %S 秒(00-59) 9 %a 本地簡化星期名稱 10 %A 本地完整星期名稱 11 %b 本地簡化的月份名稱 12 %B 本地完整的月份名稱 13 %c 本地相應的日期表示和時間表示 14 %j 年內的一天(001-366) 15 %p 本地A.M.或P.M.的等價符 16 %U 一年中的星期數(00-53)星期天爲星期的開始 17 %w 星期(0-6),星期天爲星期的開始 18 %W 一年中的星期數(00-53)星期一爲星期的開始 19 %x 本地相應的日期表示 20 %X 本地相應的時間表示 21 %Z 當前時區的名稱 22 %% %號自己
(3)元組(struct_time) :struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天等)
首先, 咱們先導入time模塊, 來認識一下python中表示的幾種格式:
impo time 進入模塊 # 時間戳時間 # print(time.time()) # 格式化時間 # print(time.strftime('%Y-%m-%d %H:%M:%S')) # str format time # print(time.strftime('%y-%m-%d %H:%M:%S')) # str format time # print(time.strftime('%c')) # 結構化時間 # struct_time = time.localtime() # 北京時間 # print(struct_time) # print(struct_time.tm_mon) # 時間戳換成字符串時間 # print(time.time()) # struct_time = time.localtime(1500000000) # # print(time.gmtime(1500000000)) # ret = time.strftime('%y-%m-%d %H:%M:%S',struct_time) # print(ret) # 字符串時間 轉 時間戳 # struct_time = time.strptime('2018-8-8','%Y-%m-%d') # print(struct_time) # res = time.mktime(struct_time) # print(res)
小結:時間戳是計算機可以識別的時間 ; 時間字符串是人能看懂的時間 ; 元祖則是用來操做時間的
幾種格式之間的轉換:
#時間戳-->結構化時間 #time.gmtime(時間戳) #UTC時間,與英國倫敦當地時間一致 #time.localtime(時間戳) #當地時間。例如咱們如今在北京執行這個方法:與UTC時間相差8小時,UTC時間+8小時 = 北京時間 >>>time.gmtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) >>>time.localtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) #結構化時間-->時間戳 #time.mktime(結構化時間) >>>time_tuple = time.localtime(1500000000) >>>time.mktime(time_tuple) 1500000000.0 複製代碼
#結構化時間-->字符串時間 #time.strftime("格式定義","結構化時間") 結構化時間參數若不傳,則顯示當前時間 >>>time.strftime("%Y-%m-%d %X") '2017-07-24 14:55:36' >>>time.strftime("%Y-%m-%d",time.localtime(1500000000)) '2017-07-14' #字符串時間-->結構化時間 #time.strptime(時間字符串,字符串對應格式) >>>time.strptime("2017-03-16","%Y-%m-%d") 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) >>>time.strptime("07/24/2017","%m/%d/%Y") 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)
#結構化時間 --> %a %b %d %H:%M:%S %Y串 #time.asctime(結構化時間) 若是不傳參數,直接返回當前時間的格式化串 >>>time.asctime(time.localtime(1500000000)) 'Fri Jul 14 10:40:00 2017' >>>time.asctime() 'Mon Jul 24 15:18:33 2017' #時間戳 --> %a %b %d %H:%M:%S %Y串 #time.ctime(時間戳) 若是不傳參數,直接返回當前時間的格式化串 >>>time.ctime() 'Mon Jul 24 15:19:07 2017' >>>time.ctime(1500000000) 'Fri Jul 14 10:40:00 2017'
練習題:
# 1.查看一下2000000000時間戳時間表示的年月日 # 時間戳 - 結構化 - 格式化 # struct_t = time.localtime(2000000000) # print(struct_t) # print(time.strftime('%y-%m-%d',struct_t)) # 2.將2008-8-8轉換成時間戳時間 # t = time.strptime('2008-8-8','%Y-%m-%d') # print(time.mktime(t)) # 3.請將當前時間的當前月1號的時間戳時間取出來 - 函數 # 2018-8-1 # def get_time(): # st = time.localtime() # st2 = time.strptime('%s-%s-1'%(st.tm_year,st.tm_mon),'%Y-%m-%d') # return time.mktime(st2) # print(get_time()) # 4.計算時間差 # 2018-8-19 22:10:8 2018-8-20 11:07:3 # 通過了多少時分秒 # str_time1 = '2018-8-19 22:10:8' # str_time2 = '2018-8-20 11:07:3' # struct_t1 = time.strptime(str_time1,'%Y-%m-%d %H:%M:%S') # struct_t2 = time.strptime(str_time2,'%Y-%m-%d %H:%M:%S') # timestamp1 = time.mktime(struct_t1) # timestamp2 = time.mktime(struct_t2) # sub_time = timestamp2 - timestamp1 # gm_time = time.gmtime(sub_time) # # 1970-1-1 00:00:00 # print('過去了%d年%d月%d天%d小時%d分鐘%d秒'%(gm_time.tm_year-1970,gm_time.tm_mon-1, # gm_time.tm_mday-1,gm_time.tm_hour, # gm_time.tm_min,gm_time.tm_sec)) # # print(time.strftime("%y-%m-%d ")) # print(time.strftime("%y-%m-%d %H-%M-%S"))
sys模塊 (impor sys)
sys模塊是與python解釋器交互的一個接口
sys.argv 命令行參數List,第一個元素是程序自己路徑 sys.exit(n) 退出程序,正常退出時exit(0),錯誤退出sys.exit(1) sys.version 獲取Python解釋程序的版本信息 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform 返回操做系統平臺名稱
模塊地址的導入
import re # sys.modules # print(sys.modules) # 是咱們導入到內存中的全部模塊的名字 : 這個模塊的內存地址 # print(sys.modules['re'].findall('\d','abc126'))
os模塊(import 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.stat('path/filename')獲取文件/目錄信息的結構說明
import os # 把路徑中不符合規範的/改爲操做系統默認的格式 # path = os.path.abspath('D:/sylar/s15/day19/4.os模塊.py') # print(path) # 可以給能找到的相對路徑改爲絕對路徑 # path = os.path.abspath('4.os模塊.py') # print(path) # 就是把一個路徑分紅兩段,第二段是一個文件/文件夾 # path= os.path.split('D:/sylar/s15/day19/4.os模塊.py') # print(path) # path= os.path.split('D:/sylar/s15/day19') # print(path) # ret1 = os.path.dirname('D:/sylar/s15/day19/4.os模塊.py') # ret2 = os.path.basename('D:/sylar/s15/day19/4.os模塊.py') # print(ret1) # print(ret2) # 若是你兩個值都須要 os.path.split # 若是你只要一個值 os.path.dirname/os.path.basename # 判斷文件/文件夾是否存在 # res = os.path.exists(r'D:\sylar\s15\day19\4.os模塊.py') # print(res) # res1 = os.path.isabs('4.os模塊.py') # res2 = os.path.isabs(r'D:\sylar\s15\day19\4.os模塊.py') # print(res1) # print(res2) # print(os.listdir('D:\sylar\s15')) # print(os.path.isdir(r'D:\sylar\s15\aaa')) # print(os.path.isfile(r'D:\sylar\s15\aaa')) # print(os.path.isfile('D:\sylar\s15\day01')) # print(os.path.isdir('D:\sylar\s15\day01')) # path = os.path.join('D:\sylar\s15','bbb') # print(path) # size= os.path.getsize(r'D:\sylar\s15\day19\4.os模塊.py') # 查看文件大小 # print(size) # ret1 = os.path.getsize('D:\sylar\s15\day19') # ret2 = os.path.getsize('D:\sylar\s15\day18') # ret3 = os.path.getsize('D:\sylar\s15\day17') # ret4 = os.path.getsize('D:\sylar\s15') # print(ret1,ret2,ret3,ret4) # 全部的文件夾 都至少是4096個字節 # 8192 # 64字節 + 32字節/新文件
stat 結構: st_mode: inode 保護模式 st_ino: inode 節點號。 st_dev: inode 駐留的設備。 st_nlink: inode 的連接數。 st_uid: 全部者的用戶ID。 st_gid: 全部者的組ID。 st_size: 普通文件以字節爲單位的大小;包含等待某些特殊文件的數據。 st_atime: 上次訪問的時間。 st_mtime: 最後一次修改的時間。 st_ctime: 由操做系統報告的"ctime"。在某些系統上(如Unix)是最新的元數據更改的時間,在其它系統上(如Windows)是建立時間(詳細信息參見平臺的文檔)。
os.sep 輸出操做系統特定的路徑分隔符,win下爲"\\",Linux下爲"/" os.linesep 輸出當前平臺使用的行終止符,win下爲"\t\n",Linux下爲"\n" os.pathsep 輸出用於分割文件路徑的字符串 win下爲;,Linux下爲: os.name 輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix'
# 使用python代碼統計一個文件夾中全部文件的總大小 # 你須要統計文件夾大小 # D:\sylar\s15\ 文件夾的大小 # 拿到這個文件夾下全部的文件夾 和 文件 # 是文件就取大小 # 是文件夾 再打開這個文件夾 : 文件/文件夾 # 遞歸 # def func(path): # r'D:\sylar\s15' # size_sum = 0 # name_lst = os.listdir(path) # for name in name_lst: # path_abs = os.path.join(path,name) # if os.path.isdir(path_abs): # size = func(path_abs) # size_sum += size # else: # size_sum += os.path.getsize(path_abs) # return size_sum # # ret = func(r'D:\sylar\s15') # print(ret) # def func(path): # D:\sylar\s15 # size_sum = 0 # 0 # name_lst = os.listdir(path) # ['day01','day02',...] # for name in name_lst: # 'day01' 'day02' # path = os.path.join(path,name) # 'D:\sylar\s15\day01' # if os.path.isdir(path): # True # size = func(path) # func('D:\sylar\s15\day01') # size_sum += size # else: # size_sum += os.path.getsize(path) # return size_sum # # def func(path): # 'D:\sylar\s15\day02' # size_sum = 0 # sum = 0 # name_lst = os.listdir(path) # [first.py...] # for name in name_lst: # first.py 100 # path = os.path.join(path,name) # if os.path.isdir(path): # func(path) # else: # 文件 # size_sum += os.path.getsize(path) # sizesum += 100 = 100+100+100+100 = 500 # return size_sum # return 500 # 循環 # 堆棧思想 # 列表 知足一個順序 先進來的後出去 # lst = [r'D:\sylar\s15',] # 列表的第一個目錄就是我要統計的目錄 # size_sum = 0 # while lst: # [r'D:\sylar\s15',] lst = ['D:\sylar\s15\day01','D:\sylar\s15\day01'..] # path = lst.pop() # path = 'D:\sylar\s15' lst = [] # path_list = os.listdir(path) # path_list = ['day01',day02',aaa,day15.py] # for name in path_list: # name = day01 # abs_path = os.path.join(path,name) # if os.path.isdir(abs_path): # 文件夾的邏輯 # lst.append(abs_path) # lst.append('D:\sylar\s15\day01') lst = ['D:\sylar\s15\day01'] # else: # size_sum += os.path.getsize(abs_path) # print(size_sum)