20181205(模組迴圈匯入解決方案,json&pickle模組,time,date,random介紹)
阿新 • • 發佈:2018-12-05
一、補充內容
迴圈匯入
解決方案:
1、將匯入的語句挪到後面。
2、將匯入語句放入函式,函式在定義階段不執行
#m1.py
print('正在匯入m1') #②能夠正常列印
from m2 import y #③跳轉到m2模組尋找y
x='m1' #此句暫未執行
#m2.py
print('正在匯入m2') #④能夠正常列印
from m1 import x #⑤此句無法正常執行,因為m1中沒有x的資料
y='m2' #此句也暫未執行
#run.py
import m1 #①匯入m1模組
解決方案一:匯入語句放到最後
#m1.py
print('正在匯入m1')
x='m1'
from m2 import y
#m2.py
print('正在匯入m2')
y='m2'
from m1 import x
解決方案二:匯入語句放到函式中
#m1.py
print('正在匯入m1')
def f1(): #在匯入m1時,函式並沒有執行
from m2 import y
print(x,y)
x = 'm1' #獲取x的值
#m2.py
print('正在匯入m2')
def f2():
from m1 import x
print(x,y)
y = 'm2'
#run.py
import m1
m1.f1()
二、包
定義:包就是一個含有__init__.py檔案的資料夾。
導包就是匯入__init__檔案中的內容
絕對匯入:以包的頂級資料夾目錄作為查詢的起始位置。
先要新增環境變數;
import sys
sys.path.append(r'C:\Users\wangt\PycharmProjects\new\20181205')
也就是說包放置在了20181205這個目錄下的某處。
後續呼叫時,可以直接呼叫,目錄均以資料夾20181205開始:
import m1 #匯入20181205資料夾下的m1模組
import aaa.m2 #匯入20181205資料夾下的aaa資料夾中的m2模組
import aaa #匯入20181205資料夾下的aaa資料夾中的所有模組 #此處假設aaa是資料夾的名字
from aaa.m2 import func1 #匯入20181205資料夾下的aaa資料夾中m2模組中的func1函式
import aaa.bbb.m3 #匯入資料夾20181205\aaa\bbb下的m3模組
#######此處存疑######相對匯入:僅限在包內用,只能用於包內的模組互相引用。
.代表當前資料夾,..代表上一級資料夾,...代表上上級資料夾,以此類推。
import m1 #匯入當前資料夾下的m1模組
import .m2 #匯入當前資料夾的上一級資料夾中的m2模組
from ..m3 import func1 #匯入當前資料夾的上一級資料夾的上一級資料夾中的m2模組中的func1函式
三、json&pickle模組
目的:為了解決序列化問題
序列化定義:序列化就是將記憶體中的資料型別轉換成另外一種格式。
即: 字典----序列化---》其他格式---》--------》存到硬碟
硬碟------讀取---》其他格式---反序列化-----》字典
序列化的目的:
1、持久儲存程式的執行狀態
2、資料的跨平臺互動
序列化的使用:
json(最常用):
優點:這種格式是一種通用的格式,所有程式語言都能識別。跨平臺性好。
缺點:不能識別所有python型別(例如不能識別集合)
強調:json不能識別單引號,是能識別雙引號。
pickle:
優點:能識別所有python型別
缺點:只能被python這門程式語言識別
dumps和loads方法都在記憶體中轉換,dump和load的方法會多一個步驟,dump是把序列化後的字串寫到一個檔案中,而load是從一個一個檔案中讀取檔案
json儲存成字串型別,所以mode為t。
import json
dic={'k1':True,'k2':10,'k3':'egon'}
序列化:
dic_json=json.dumps(dic)
print(dic_json,type(dic_json))
輸出結果為:
{"k1": true, "k2": 10, "k3": "egon"} <class 'str'> #這是跨平臺的互動資料
持久化:
with open('a.json',mode='wt',encoding='utf8') as f:
f.write(dic_json)
從檔案中讀取json格式的字元:
with open('a.json',mode='rt',encoding='utf8') as f:
dic_json=f.read()
反序列化
dic=json.loads(dic_json)
print(dic)
序列化+持久化
with open('a.json',mode='wt',encoding='utf8') as f:
json.dump(dic,f)
讀取檔案內容+反序列化
with open('a.json',mode='rt',encoding='utf8') as f:
dic=json.load(f)
print(dic)
pickle只能資料持久化,無法跨平臺呼叫。儲存成二進位制型別,所以mode為b。
import pickle
dic={'k1':True,'k2':10,'k3':'egon'}
序列化:
dic_pkl=pickle.dumps(dic)
持久化:
with open('dic.pkl',mode='wb') as f:
f.write(dic_pkl)
讀取檔案內容及反序列化
with open('dic.pkl',mode='rb') as f:
dic_pkl=f.read()
dic=pickle.loads(dic_pkl)
print(type(dic))
序列化+持久化
with open('c.pkl',mode='wb') as f:
pickle.dump(dic,f)
讀取檔案內容+反序列化
with open('c.pkl',mode='rb') as f:
dic=pickle.load(f)
print(dic,type(dic))
四、內建模組介紹
1、time&datatime
time模組
時間分為三種格式:
1、時間戳,參考1970年的時間
print(time.time())
輸出結果為:
1544006378.4561322 #從格林威治時間1970年01月01日00時00分00秒到現在過去的秒數
2、格式化的字串
print(time.strftime('%Y-%m-%d %H:%M:%S %p')) #p是上午下午的意思。
print(time.strftime('%Y-%m-%d %H:%M:%S'))
輸出結果為:
2018-12-05 18:38:31 PM
2018-12-05 18:38:31
3、結構化的時間物件
print(time.localtime()) #當前時區時間
print(time.gmtime()) #格林尼治時間
print(time.localtime().tm_hour) #一天的第幾個小時
print(time.localtime().tm_wday) #一週的第幾天
print(time.localtime().tm_yday) #一年的第幾天
時間轉換
時間戳——》struct time——》格式化的字串時間
import time
struct_time=time.localtime(123123) #秒數轉化為結構化時間
print(struct_time)
輸出結果為:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=18, tm_min=12, tm_sec=3, tm_wday=4, tm_yday=2, tm_isdst=0)
print(time.strftime('%Y-%m-%d',struct_time)) #將結構化的時間轉換為標準格式
輸出結果為:
1970-01-02
格式化的字串——》struct_time——》時間戳
import time
struct_time=time.strptime('2018-12-05','%Y-%m-%d') #將格式化的字串時間轉換為結構化時間
print(time.mktime(struct_time)) #將結構化時間轉換為時間戳
輸出結果為:
1543939200.0
datetime模組
獲取格式化的字串的時間
import datetime
print(datetime.datetime.now()) #直接獲取當前時間
輸出結果:
2018-12-05 18:45:23.195833
print(datetime.datetime.fromtimestamp(5678989)) #將時間戳直接轉換為結構化時間的字串
輸出結果為:
1970-03-08 01:29:49
計算時間
import datetime
print(datetime.datetime.now()) #當前時間
print(datetime.datetime.now()+datetime.timedelta(days=3)) #三天後時間
print(datetime.datetime.now()+datetime.timedelta(hours=3)) #三小時後時間。 #支援weeks,days,seconds,minutes,hours,還有毫秒等,支援負號-,就是多久之前。
print(datetime.datetime.now()+datetime.timedelta(days=3,hours=3)) #三天三小時後
輸出結果為:
2018-12-05 18:54:22.206142
2018-12-08 18:54:22.206142
2018-12-05 21:54:22.206142
2018-12-08 21:54:22.206142
2、random模組
import random
print( random.randint(1,10) ) # 產生 1 到 10 的一個整數型隨機數 (包括1和10)
print( random.random() ) # 產生 0 到 1 之間的隨機浮點數
print( random.uniform(1.1,5.4) ) # 產生 1.1 到 5.4 之間的隨機浮點數,區間可以不是整數
print( random.randrange(1,100,2) ) # 生成從1到100的間隔為2的隨機整數,顧頭不顧尾,不包括100
a=[1,3,5,6,7] # 將序列a中的元素順序打亂
random.shuffle(a)
print(a)
print( random.choice('tomorrow') ) # 從序列中隨機選取一個元素
print( random.choice(['1','a','4','b']) ) # 從列表中隨機選取一個元素
print( random.sample(['1','a','4','b'],2) ) # 從列表中隨機選取兩個元素
應用:隨機驗證碼。
chr(num) 可以將數字按照ASCII錶轉換成對應得符號。
例如
print(chr(65))
print(chr(90))
print(chr(97))
print(chr(122))
輸出結果為:
A
Z
a
z
import random
res='' #空字串
for i in range(5): #迴圈五次,得到一個五位的驗證碼
num=str(random.randint(0,9)) #得到0到9的隨機數,並且改為字串型別
alp=chr(random.randint(65,90)) #對應ASCII表,得到大寫字母
res += random.choice([num,alp]) #二選一,字串性價
print(res) #輸出隨機的五位驗證碼
升級版本:
def make_code(max_size=5):
import random
res=''
for i in range(max_size):
num=str(random.randint(0,9))
alp=chr(random.randint(65,90))
res += random.choice([num,alp])
return res
print(make_code(10)) #指定驗證碼長度