Python hash、xml、configparser、sheve、shutil模組講解 以及 物件導向初識

來源:互聯網
上載者:User

標籤:skill   SHA256   dal   原材料   刪除   世界   方式   find   包括   

今日內容:

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

類的代碼會在類定義階段就立即執行,會產生一個類的名稱空間
類的本身就是一個容器/名稱空間,是用來存放名字的,這是類的用途之一

Python hash、xml、configparser、sheve、shutil模組講解 以及 物件導向初識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.