Python hash、xml、configparser、sheve、shutil模块讲解 以及 面向对象初识
今日內容:
1.hash模塊
2.xml模塊
3.configparser模塊
4.sheve 模塊
5.shutil模塊
?
知識點一:hash
什么是hash:
?hash是一種算法,該算法接受傳入的的內容,經過運算得到一串hash如果把hash算法比喻一座工廠
?那傳給hash算法的內容就是原材料,生產的hash值就是生產出的產品
?
為何用hash算法:
?hash值產品有三大特性:
?1.只要傳入的內容一樣,得到的hash值必然是一樣的
?2.只要我們使用的hash算法固定,無論傳入的內容有多大得到的hash值得長度是固定的
?3.不可以用hash值逆推原來的內容
?基于1和2可以在下載文件時做文件一致性校驗
?基于1和3可以對密碼進行加密
?
?
# 例如:
import hashlib
password=input('密碼:')
m=hashlib.md5('天王蓋地虎'.encode('utf-8'))? #可以多一層復雜性加密
m.update(password.encode('utf-8'))
print(m.hexdigest())
'''
結果:
密碼:123
41046ee2686f6c698c859a13b47cdb1f
'''
import hashlib
# 用法1:
#1.造工廠
m=hashlib.md5()???? #m=hashlib.sha256() 可以是其他加密個是
#2.運送材料
m.update('你好啊'.encode('utf-8'))
#3.產出hash值
print(m.hexdigest())? #124756ef340daf80196b4124686d651c
#用法2:
m=hashlib.md5('你'.encode('utf-8')) #可以在造工廠的時候就添加材料
m.update('好啊'.encode('utf-8'))?
print(m.hexdigest())? #124756ef340daf80196b4124686d651c?? hash結果:和上面一樣,因為傳入的材料是一樣的
?
?
知識點二:xml
xml是實現不同語言或程序之間進行數據交換的協議,跟json差不多,
但json使用起來更簡單
xml的格式如下,就是通過<>節點來區別數據結構的:
xml模塊:
?1.標簽名? root.tag
?2.便簽屬性 root.attrib
?3.標簽文本 root.text
以xml.xml文件為例:
<data>
??? <country name="Liechtenstein">
??????? <rank updated="yes">2</rank>
??????? <year>2008</year>
??????? <gdppc>141100</gdppc>
??????? <neighbor direction="E" name="Austria" />
??????? <neighbor direction="W" name="Switzerland" />
??? </country>
??? <country name="Singapore">
??????? <rank updated="yes">5</rank>
??????? <year>2011</year>
??????? <gdppc>59900</gdppc>
??????? <neighbor direction="N" name="Malaysia" />
??? </country>
??? <country name="Panama">
??????? <rank updated="yes">69</rank>
??????? <year>2011</year>
??????? <gdppc>13600</gdppc>
??????? <neighbor direction="W" name="Costa Rica" />
??????? <neighbor direction="E" name="Colombia" />
??? </country>
</data>
可以對xml文件進行一下操作:
import xml.etree.ElementTree as ET
tree=ET.parse('xml.xml')??????? #parse單詞:從語法上分析 理解
root = tree.getroot()
#對任何標簽都有三個特征:便簽名、標簽屬性、標簽的文本內容
print(root.tag)??? #data
print(root.attrib)? #標簽屬性 {}
print(root.text)? #標簽文本? 空
print(list(root.iter('year')))
print(root.iter('year'))
for year in root.iter('year'):
??? print(year.tag)
??? print(year.attrib)
??? print(year.text)
??? print('========================')
# 在root的子節點找,只找一個
print(root.find('country').attrib)???? #{'name': 'Liechtenstein'}
print(root.findall('country'))???? #[<Element 'country' at 0x055F5CC0>,.. 列表格式
# 在root的子節點找,找所有
# 列表推導式,找出所有二級country本身的屬性
print([country.attrib for country in root.findall('country')])
for country in root.findall('country'):
?? print(country.attrib)
# 結果:
'''
{'name': 'Liechtenstein'}
{'name': 'Singapore'}
{'name': 'Panama'}
'''
# 1.查
# 遍歷整個文檔
for country in root:
??? # print('========>國家%s'%country.attrib)
??? for item in country:
??????? print(item.tag)???????????????????????????????????????????? #year??? #rank
??????? print(item.attrib)????? #<year>2008</year>屬性標簽為空:{}? #{}????? #{'updated': 'yes'}
??????? print(item.text)?? #<year>2008</year>文本標簽為2008???????? #2018??? #2
# 2.改
for year in root.iter('year'):
??? print(year.tag)? #year year year
??? year.attrib={'update':'yes'}
??? year.text=str(int(year.text)+1)
tree.write('xml.xml')
# 3.增加
for country in root:
??? rank=country.find('rank')
??? if int(rank.text)>50:
??????? tag=ET.Element('egon')??????? #element單詞意思:元素?? 是否意思為增加一個名為egon的標簽???
??????? tag.attrib={'update':'yes'}
??????? tag.text='NB'
??????? country.append(tag)
tree.write('xml.xml')
# 4.刪除
for country in root:
??? tag=country.find('egon')
??? # print(tag)???????????? #前兩個country下面沒有egon,所有沒提示 None
??? if tag is not None:
??????? print('====>')
??????? country.remove(tag)
tree.write('xml.xml')
?
知識點三:configparser模塊(解析配置文件)
主要所有三項:
?1.config.sections? 查看標題
?2.config.options?? 查看指定標題下面所有key=value的key值
?3.config.get?????? 查看指定標題下面key=value的value值
?4.config.items???? 查看取所有key、value的值以(key,value)格式顯示
以文件config.ini格式為例:
[egon]
sex='female'
age=20
salary=31
is_auth=True
[alex]
sex='male'
age=20
salary=1
is_auth=True
可以進行一下操作:
import configparser
config=configparser.ConfigParser()
config.read('config.ini')
取標題
print(config.sections())?? # ["'egon'", "'alex'"]
取文件標題下面下所有key=value的key
print(config.options('egon'))? #['sex', 'age', 'salary', 'is_auth']
取文件標題下面指定的key=value的value
print(config.get('egon','age'))? #20
取所有key=value的(key,value)格式
print(config.items('egon'))
[('sex', "'female'"), ('age', '20'), ('salary', '31'), ('is_auth', 'True')]
?
?
?
知識點四:sheve 模塊(序列化和反序列化)
shelve更簡單,也支持所有的的數據類型,但只能在python里面用
import shelve
f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
f['stu2_info']={'name':'gangdan','age':53}
1.存文件
f=shelve.open(r'shelve.txt')
2.取文件
print(f['stu1_info']['hobby'])
print(f['stu2_info']['name'])
3.改文件內容
注意點:
f['stu1_info']['age']=44444? 這樣看是賦值改動,但是實際沒有改,因為沒有寫入的文件
print(f['stu1_info'])
要想寫入,需要添加,writeback=True 將修改的文件寫回后臺文件
f=shelve.open(r'shelve.txt',writeback=True)
f['stu1_info']['age']=44444
print(f['stu1_info'])
'''
輸出結果為:
{'name': 'egon', 'age': 44444, 'hobby': ['piao', 'smoking', 'drinking']}
?
?
?
知識點五:shutill模塊
高級的 文件、文件夾、壓縮包 處理模塊
import shutil
拷貝文件
方式一:
with open('config.ini','r')as read_f,open('new.xml','w') as write_f:
??? shutil.copyfileobj(read_f,write_f)
方式二:shutil.copyfile(src, dst)
源文件事先定義好,目標文件無需存在,
shutil.copyfile('new.xml', r'E:\f2.log') #拷貝到指定文件
shutil.copyfile('new.xml', 'f2.log')? #拷貝到當前文件夾
僅拷貝文件權限,內容、組、用戶均不變? shutil.copymode(src, dst)
目標文件均不變,只是文件權限變動
shutil.copymode('new.xml', 'f2.log')
僅拷貝狀態信息,包括:mode bits, atime, mtime, flags
shutil.copystat('new.xml', r'E:\f2.log')
拷貝文件和權限
import shutil
shutil.copy('f1.log', 'f2.log')
遞歸的去拷貝文件夾
import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目標目錄不能存在,
# 注意對folder2目錄父級目錄要有可寫權限,ignore的意思是排除
遞歸的取刪除文件
import shutil
shutil.rmtree('folder1')
#遞歸的去移動文件夾 shutil.move(src, dst)
import shutil
shutil.move('folder1', 'folder3')
創建壓縮包并返回文件路徑
import shutil
'''
1.base_bak: 壓縮后文件的名字,壓縮包的文件名(也可以指定壓縮好保存的具體文件目錄)
??? 如 data_bak=>保存至當前路徑
??? 如:/tmp/data_bak =>保存至/tmp/
2.gztar: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
3.root_dir: 被壓縮文件的路徑(默認當前目錄)
4.owner: 用戶,默認當前用戶
5.group: 組,默認當前組
6.logger: 用于記錄日志,通常是logging.Logger對象
'''
#res=shutil.make_archive('data_bak','gztar',root_dir=r'E:\PycharmProjects\untitled\day17\包練習')
#解壓文件(解壓上面剛剛壓縮的文件)
import tarfile
t=tarfile.open(r'E:\PycharmProjects\untitled\day20\data_bak.tar.gz','r') #源文件路徑
t.extractall(r'E:\PycharmProjects\untitled\day20\dir_tarfile') #解壓后文件存放路徑
t.close()
?
知識點六:面向對象
面向對象編程:
對象:特征與技能的集合體,上帝的思維方式
優點:
?可擴展性強
缺點:
?編程的復雜程度要高于面向過程
類;類是一系列具有相同特征、技能對象的集合體
強調:站的角度不同,總結出來的來是截然不同的
現實世界中:先有對象,后才有類
在程序中:必須先定義類,后調用類來產生對象
《類里面盡量用駝峰體》
面向對象初始模板:
class OldboyStudent:?? #類的名稱OldboyStudent
??? school='Oldboy'??? #特征(變量表示)
??? def learn(self):?? #就是一個普通函數
??????? print('is learn skill')? #技能1(函數表示)
??? def choice(self):
??????? print('choose course')?? #技能2(函數表示)
print(OldboyStudent)? #<class '__main__.OldboyStudent'>
print(OldboyStudent.__dict__)? #輸出結果:如下
{'__module__': '__main__', 'school': 'Oldboy', 'learn':
<function OldboyStudent.learn at 0x05A9D810>, 'choice': <function OldboyStudent.choice at 0x05A9D7C8>,
'__dict__': <attribute '__dict__' of 'OldboyStudent' objects>, '__weakref__': <attribute '__weakref__' of
?'OldboyStudent' objects>, '__doc__': None}
Oldboy
print(OldboyStudent.__dict__['school'])?? #'school'是以字符串傳值得
print(OldboyStudent.school)
OldboyStudent.learn(123)? #OldboyStudent.learn('aaa')
注意理解:
OldboyStudent.learn(123) .后面跟的是類里面的屬性,可以是變量名school和函數名learn
類的代碼會在類定義階段就立即執行,會產生一個類的名稱空間
類的本身就是一個容器/名稱空間,是用來存放名字的,這是類的用途之一
轉載于:https://www.cnblogs.com/yangzhizong/p/9225668.html
總結
以上是生活随笔為你收集整理的Python hash、xml、configparser、sheve、shutil模块讲解 以及 面向对象初识的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高通QFil刷机经验
- 下一篇: 学习笔记(46):Python实战编程-