python學習(十三)——模組time、random、os、sys、json、re
阿新 • • 發佈:2018-12-15
一、概念
模組
1、三種類型:
(1)python標準庫
(2)第三方模組
(3)自定義模組
2、匯入
(1)import:
1)執行;2)呼叫
(2)from __ import * (不推薦)
(3)執行對應檔案
__init__.py
包
呼叫要到模組,才能用
(1)__name__:名稱,路徑
(2)if __name = "__main__": :執行函式
二、模組
1、time
(1)時間戳(1970年1月1日凌晨開始)
# 時間戳 #計算 print(time.time()) #1481321748.481654秒
(2)結構化時間
# 結構化時間---當地時間
print(time.localtime(1531242343))
t=time.localtime()
print(t.tm_year)
print(t.tm_wday)
# -----#結構化時間---UTC
print(time.gmtime())
(3)將結構化時間轉換成時間戳
# -----將結構化時間轉換成時間戳 print(time.mktime(time.localtime())) # ------將結構化時間轉成字串時間strftime print(time.strftime("%Y---%m-%d %X",time.localtime())) # ------將字串時間轉成結構化時間strptime print(time.strptime("2016:12:24:17:50:36","%Y:%m:%d:%X")) print(time.asctime()) # 結構化時間轉換 print(time.ctime()) # 時間戳轉換 #比較實用 import datetime print(datetime.datetime.now())
2、random
(1)功能
import random ret=random.random() # 0-1的隨機數 ret=random.randint(1,3) # 1-3之間的整數 ret=random.randrange(1,3) # 1,2 ret=random.choice([11,22,33,44,55]) # 隨機選一個 ret=random.sample([11,22,33,44,55],2) # 隨機選兩個 ret=random.uniform(1,4) # 隨機浮點型 print(ret) ret=[1,2,3,4,5] random.shuffle(ret) #打亂順序 print(ret)
(2)驗證碼
def v_code():
ret=""
for i in range(5):
num=random.randint(0,9)
alf=chr(random.randint(65,122))
s=str(random.choice([num,alf]))
ret+=s
return ret
print(v_code())
3、os模組
(1)功能
os.getcwd() # 當前工作路徑
os.chdir("..") # 改變當前工作目錄(..返回上一層)
print(os.getcwd())
os.makedirs('dirname1/dirname2') # 建立資料夾
os.removedirs("dirname1/dirname2") # 刪除資料夾(有內容就不刪)
print(os.listdir()) # 當前目錄列表
print(os.stat("sss.py")) # sss.py的屬性資訊
print(os.system("dir"))
print(os.path.split(r"C:\Users\Administrator\脫產三期\day22\sss.py"))
print(os.path.dirname(r"C:\Users\Administrator\脫產三期\day22\sss.py"))
print(os.path.basename(r"C:\Users\Administrator\脫產三期\day22\sss.py"))
a="C:\Users\Administrator"
b="脫產三期\day22\sss.py"
os.path.join(a,b)# 路徑拼接
#coding=utf-8
import os #匯入OS模組
os.getcwd() #得到當前工作目錄
os.listdir() #指定所有目錄下所有檔案和目錄
os.remove() #刪除目錄
os.rmdir() #刪除目錄
os.mkdir() #建立目錄
os.path.isdir() #判斷指定物件是否為目錄
os.path.isfile() #判斷指定物件是否為檔案
os.path.exists() #判斷指定物件是否存在
os.path.split() #返回路徑的目錄和檔名
os.chdir() #改變目錄到指定目錄
os.path.getsize() #獲得檔案大小,如果為目錄,結果為0
os.path.abspath() #獲得絕對路徑
os.path.join(path,name) #連線目錄或檔名
os.path.basename(path) #返回檔名
os.path.dirname(path) #返回檔案路徑
4、sys
(1)功能
sys.exit() # 退出
sys.version # 獲取版本
sys.argv # 命令列引數List,第一個元素是程式本身路徑
(2)進度條
import time
for i in range(100):
sys.stdout.write("#")
time.sleep(0.1)
sys.stdout.flush() # 立即顯示
5、json
(1)功能
json.dumps() # 將資料型別轉換為json資料
dic={'name':'alex'} #---->{"name":"alex"}----->'{"name":"alex"}'
i=8 #---->'8'
s='hello' #---->"hello"------>'"hello"'
l=[11,22] #---->"[11,22]"
json.load() # 載入json資料
(2)示例
# 寫檔案
dic='{"name":"alex"}'
f=open("hello","w")
f.write(dic)
# 讀檔案
f_read=open("hello","r")
data=f_read.read()
print(type(data))
data=eval(data)
print(data["name"])
#---------------------------------------------------------------------
# json-雙引
import json
dic={'name':'alex'} #---->{"name":"alex"}----->'{"name":"alex"}'
i=8 #---->'8'
s='hello' #---->"hello"------>'"hello"'
l=[11,22] #---->"[11,22]"
f=open("new_hello","w")
dic_str=json.dumps(dic)
f.write(dic_str) #json.dump(dic,f)
# data = json.load(f)
(3)pickle(不可讀)與json幾乎一樣,只是處理為位元組-支援的型別更多,一般json
import pickle
f = open('序列化物件_pickle', 'rb')
data = pickle.loads(f.read()) # 等價於data=pickle.load(f)
print(data['age'])
6、shelve(不常用)
# # -------------------------shelve模組---------
import shelve
f = shelve.open(r'shelve1') # 目的:將一個字典放入文字 f={}
#
# f['stu1_info']={'name':'alex','age':'18'}
# f['stu2_info']={'name':'alvin','age':'20'}
# f['school_info']={'website':'oldboyedu.com','city':'beijing'}
# f.close()
print(f.get('stu1_info')['age'])
7、xml-出現晚於json
import xml.etree.ElementTree as ET
tree = ET.parse("xml_lesson")
root = tree.getroot()
print(root.tag)
for i in root:
#print(i.tag)
#print(i.attrib)
for j in i:
#print(j.tag)
#print(j.attrib)
print(j.text)
# 遍歷xml文件
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag, i.text)
# 只遍歷year 節點
for node in root.iter('year'):
print(node.tag, node.text)
# ---------------------------------------
import xml.etree.ElementTree as ET
tree = ET.parse("xml_lesson")
root = tree.getroot()
# 修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set("updated", "yes")
tree.write("xml_lesson")
# 刪除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
et = ET.ElementTree(new_xml) # 生成文件物件
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml) # 列印生成的格式
8、re(正則表示式)-操作字串 -模糊匹配
# ---------------------------功能------------------------------
re.findall('a', 'asdasda') # 返回所有滿足匹配條件的結果,放在列表裡
re.search('a', 'asdasda').group()
re.match('a', 'asdasda').group() # 同search,不過只在字串開始處匹配
re.split('[ab]', 'absd') # 先按'a'分割得到''和'bsd'分別按'b'分割
# ['', '', 'sd']
re.sub('\d', 'abc', 'alvinSyuan6', 1) # 替換字元 (1次)
re.subn('\d', 'abc', 'alvinSyuan6', 1) # 替換了多少次
com = re.compile("\d+")
com.findall("asdasdwda45472")
元字元 . ^ $ * + ? {} [] () \
(1)萬用字元 .
# . 萬用字元-除了換行(/n)其他都可以匹配
re.findall("asda", "asdfefs")
re.findall("a.d", "asdfefs") # 一個.代表一個字元
(2)^ -只能在字串開頭匹配
# 必須放在開頭
re.findall("^a..a", "asdaasdasdasdasdweqw")
(3)$ -只能在字串結尾匹配
# 必須放在結尾
re.findall("^a..a$", "asdaasdasdasdasdweqw")
(4)重複- * + ? {}
# * 0到無窮次(可以沒有)-貪婪匹配
re.findall("d*", "asdaasdasdasdasdweqw")
# + 1到無窮次(至少有一個) -貪婪匹配
re.findall("asdx+", "asdefxxxxxx")
# ? 0或1次
re.findall("asdxl?", "asdxxxlxxx")
# {} {0,}==* {1,}==+ {0,1}==? {6}重複6次
re.findall("asdx{6}", "asdxxxlxxx")
#------------------------貪婪轉惰性--------------------------
# 後面加個?
re.findall("asdx+?", "asdefxxxxxx") # 惰性匹配,只匹配一次
(5)[] 字符集-只能在字串結尾匹配
# [] 或;裡面沒有特殊符號,除了4個- ^ \
re.findall("x[yz*]p", "xypuuuuxzpuuu")
# - 至
re.findall("q[a-z]*", "qweeedfs")
# ^ 非
re.findall("\([^()]*\)", "12+(34*6+2-5*(2-1))")
# (2-1)
# \ 轉義符號
# \d 任何十進位制數字
# \D 任何非數字字元
# \s 任何空白字元
# \S 任何非空白字元
# \w 任何字母數字和_
# \W 任何非字母數字_
# \b 特殊字元邊界,空格,&,#等
(6)r-python這一層不做任何翻譯,只取原生字元(補充,不是元字元)
# r
re.findall(r"I\b", "I am")
(7)| -或
re.findall(r"ka|bc", "qweqka|bcasd")
# ['ka', 'bc']
(8)() -分組
# 只找第一個,返回物件
re.search("\d+", "sdasd35asdasda78")
# 取出結果
re.search("\d+", "sdasd35asdasda78").group()
# '35'
# 分組命名
re.search("(?P<name>[a-z]+)\(?P<age>\d+)", "abex36asde34asdasd33").group("age")
9、logging
(1)方法
import logging
#------------------basicConfig-----------------------------
logging.basicConfig(
level = logging.DEBUG, # 日誌級別
filename = "logger.log", # 寫入檔案
filemode = "w", # 預設追加,不追加
# 時間,檔名,行號,資訊
format = "%(asctime)s %(filename)s [%(lineno)] %(message)s"
)
logging.debug()
logging.info()
logging.warning()
logging.error()
logging.critical()
#-------------------logger-------------------------------多用
logger = logging.getLogger() # 獲取日誌
fh = logging.FileHandler("test_log") # 向檔案傳送日誌
ch = logging.StreamHandler() # 向螢幕傳送日誌
fm = logging.Formatter("%(asctime)s %(message)s")
fh.setFormatter(fm)
ch.setFormatter(fm)
logger.addHandler(fh)
logger.addHandler(ch)
logger.setLevel("DEBUG")
logging.debug("q")
logging.info("q")
logging.warning("q")
logging.error("q")
logging.critical("q")
10、configparser -為了配置檔案而開發
11、hashlib -用於加密相關的操作