Today's content:
1.hash Module
2.xml Module
3.configparser Module
4.sheve Module
5.shutil Module
Knowledge Point one: hash
What is a hash:
Hash is an algorithm, the algorithm accepts the incoming content, after the operation to get a string of hash if the hash algorithm analogy to a factory
The content that is passed to the hash algorithm is the raw material, the production of the hash value is the production of products
Why use the hash algorithm:
Hash value products have three main features:
1. As long as the incoming content, the resulting hash value must be the same
2. As long as we use the hash algorithm fixed, no matter how much the incoming content to get the hash worth the length is fixed
3. You cannot reverse the original content with a hash value
Based on 1 and 2 file consistency check can be done when downloading files
Passwords can be encrypted based on 1 and 3
For example
Import Hashlib
Password=input (' Password: ')
M=hashlib.md5 (' King of the Land Tiger ' encode (' Utf-8 ')) #可以多一层复杂性加密
M.update (Password.encode (' Utf-8 '))
Print (M.hexdigest ())
‘‘‘
Results:
Password: 123
41046ee2686f6c698c859a13b47cdb1f
‘‘‘
Import Hashlib
# usage 1:
#1. Factory Building
M=HASHLIB.MD5 () #m =hashlib.sha256 () can be other encryption is
#2. Shipping Materials
M.update (' Hello '. Encode (' Utf-8 '))
#3. Output hash value
Print (M.hexdigest ()) #124756ef340daf80196b4124686d651c
#用法2:
M=HASHLIB.MD5 (' You '. Encode (' Utf-8 ')) #可以在造工厂的时候就添加材料
M.update (' good '. Encode (' Utf-8 '))
Print (M.hexdigest ()) #124756ef340daf80196b4124686d651c hash Result: Same as above, because the incoming material is the same
Knowledge Point two: XML
XML is a protocol that implements data exchange between different languages or programs, similar to JSON,
But JSON is easier to use.
The format of XML is as follows: by the <> node to distinguish the data structure.
XML module:
1. Label name Root.tag
2. Note Properties Root.attrib
3. Label Text Root.text
Take the Xml.xml file as an example:
<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>
You can do something about the XML file:
Import Xml.etree.ElementTree as ET
Tree=et.parse (' Xml.xml ') #parse单词: grammatical analysis of comprehension
root = Tree.getroot ()
#对任何标签都有三个特征: Signature, label attribute, label text content
Print (Root.tag) #data
Print (Root.attrib) #标签属性 {}
Print (root.text) #标签文本 empty
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 (' ======================== ')
# Find a child in root and find only one
Print (Root.find (' country '). attrib) #{' name ': ' Liechtenstein '}
Print (Root.findall (' Country ')) #[<element ' Country ' at 0x055f5cc0>,.. list format
# in Root's child node, look for all
# list derivation to find the properties of all level two country itself
Print ([Country.attrib for Country in Root.findall (' Country ')])
For country in Root.findall (' Country '):
Print (Country.attrib)
Results
‘‘‘
{' name ': ' Liechtenstein '}
{' name ': ' Singapore '}
{' name ': ' Panama '}
‘‘‘
# 1.
# traverse the entire document
for country in root:
# print (' ========> country%s '%country.attrib)
for item in country:
print (Item.tag) #year #rank
Print (Item.attrib) #<year>2008</year> property label is empty:{} #{} #{' updated ': ' Yes '
print (item.text) #<year>2008</year> text label for 2008 #2018 #2
# 2. Change
For year in Root.iter (' year '):
Print (Year.tag) #year year
year.attrib={' update ': ' Yes '
YEAR.TEXT=STR (int (year.text) +1)
Tree.write (' Xml.xml ')
# 3. Increase
For country in Root:
Rank=country.find (' rank ')
if int (rank.text) >50:
Tag=et. Element (' Egon ') #element单词意思: Do the elements mean to add a label named Egon???
tag.attrib={' update ': ' Yes '
tag.text= ' NB '
Country.append (TAG)
Tree.write (' Xml.xml ')
# 4. Delete
For country in Root:
Tag=country.find (' Egon ')
# Print (tag) #前两个country下面没有egon, all without prompting none
If tag is not None:
Print (' ====> ')
Country.remove (TAG)
Tree.write (' Xml.xml ')
Knowledge Point three: Configparser module (parsing configuration file)
All three main items:
1.config.sections View Title
2.config.options View key values for all Key=value under the specified caption
3.config.get view value values for Key=value under the specified heading
4.config.items View the value of all key, value in (key,value) format display
Take the file Config.ini format as an example:
[Egon]
sex= ' Female '
Age=20
Salary=31
Is_auth=true
[Alex]
sex= ' Male '
Age=20
Salary=1
Is_auth=true
You can do the following:
Import Configparser
Config=configparser. Configparser ()
Config.read (' Config.ini ')
Take title
Print (Config.sections ()) # ["' Egon '", "' Alex '"]
Take all key=value keys under the file title
Print (Config.options (' Egon ')) #[' sex ', ' age ', ' salary ', ' Is_auth ']
Fetch the value of the key=value specified below the file title
Print (Config.get (' Egon ', ' age ')) #20
Take all Key=value (key,value) formats
Print (Config.items (' Egon '))
[(' Sex ', ' ' Female '), (' Age ', ' ' ') ', (' salary ', ' + '), (' Is_auth ', ' True ')]
Knowledge Point four: Sheve module (serialization and deserialization)
Shelve is simpler and supports all data types, but only in Python
Import shelve
f[' stu1_info ']={' name ': ' Egon ', ' age ':, ' hobby ': [' piao ', ' smoking ', ' drinking ']}
f[' stu2_info ']={' name ': ' Gangdan ', ' Age ': 53}
1. Save File
F=shelve.open (R ' Shelve.txt ')
2. Fetching files
Print (f[' stu1_info ' [' Hobby '])
Print (f[' stu2_info ' [' Name '])
3. Change the contents of the file
Note the point:
f[' Stu1_info ' [' Age ']=44444 This is an assignment change, but it's not actually changed because there are no files written
Print (f[' stu1_info ')
To write, you need to add, writeback=true to write the modified file back to the background file
F=shelve.open (R ' Shelve.txt ', writeback=true)
f[' Stu1_info ' [' Age ']=44444
Print (f[' stu1_info ')
‘‘‘
The output is:
{' name ': ' Egon ', ' age ': 44444, ' hobby ': [' piao ', ' smoking ', ' drinking ']}
Knowledge Point Five: Shutill module
Advanced files, folders, Compression pack processing modules
Import Shutil
Copy files
Way One:
With open (' Config.ini ', ' R ') as Read_f,open (' New.xml ', ' W ') as Write_f:
Shutil.copyfileobj (Read_f,write_f)
Way two: Shutil.copyfile (SRC, DST)
The source file is defined beforehand and the target file does not exist.
Shutil.copyfile (' New.xml ', R ' E:\f2.log ') #拷贝到指定文件
Shutil.copyfile (' New.xml ', ' F2.log ') #拷贝到当前文件夹
Copy only file permissions, content, group, user unchanged Shutil.copymode (src, DST)
The target file is unchanged, only the file permission changes
Shutil.copymode (' New.xml ', ' F2.log ')
Copy only status information, including: mode bits, Atime, mtime, Flags
Shutil.copystat (' New.xml ', R ' E:\f2.log ')
Copying files and Permissions
Import Shutil
Shutil.copy (' F1.log ', ' F2.log ')
Recursive go-to-copy folder
Import Shutil
Shutil.copytree (' Folder1 ', ' Folder2 ', ignore=shutil.ignore_patterns (' *.pyc ', ' tmp* ')) #目标目录不能存在,
Note for Folder2 directory parent directory to have writable permissions, ignore means to exclude
Recursive fetch and delete files
Import Shutil
Shutil.rmtree (' Folder1 ')
#递归的去移动文件夹 shutil.move (SRC, DST)
Import Shutil
Shutil.move (' Folder1 ', ' Folder3 ')
Create a compressed package and return the file path
Import Shutil
‘‘‘
1.base_bak: The name of the compressed file, the file name of the compressed package (you can also specify the specific file directory to compress the saved)
such as data_bak=> save to current path
such as:/tmp/data_bak = Save to/tmp/
2.gztar: Compressed package type, "Zip", "tar", "Bztar", "Gztar"
3.root_dir: Path of the compressed file (default current directory)
4.owner: User, default Current user
5.group: Group, default current group
6.logger: Used for logging, usually logging. Logger Object
‘‘‘
#res =shutil.make_archive (' Data_bak ', ' Gztar ', root_dir=r ' E:\PycharmProjects\untitled\day17\ bag Practice ')
#解压文件 (unzip the file just compressed above)
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 ()
Knowledge Point Six: Object-oriented
Object-Oriented Programming:
Objects: The collection of features and skills, the way God thinks
Advantages:
Strong scalability
Disadvantages:
Programming is much more complex than process-oriented
Class is a set of objects with the same characteristics and skills.
Emphasis: The angle of the station is different, summed up come out is very different
Real world: First object, then class
In the program: the class must be defined before the class is called to produce the object
"Use the hump as much as possible in class"
Object-oriented initial template:
Class Oldboystudent: #类的名称OldboyStudent
School= ' Oldboy ' #特征 (variable representation)
def learn (self): #就是一个普通函数
Print (' is learn skill ') #技能1 (function representation)
def choice (self):
Print (' Choose Course ') #技能2 (function representation)
Print (oldboystudent) #<class ' __main__. Oldboystudent ' >
Print (oldboystudent.__dict__) #输出结果: Below
{' __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 ' is a string to be worth
Print (Oldboystudent.school)
Oldboystudent.learn (123) #OldboyStudent. Learn (' AAA ')
Attention to understanding:
Oldboystudent.learn (123). followed by the property inside the class, which can be the variable name school and the function name learn
Class code is executed immediately at the class definition stage, resulting in the namespace of a class
The class itself is a container/namespace, which is used to store the name, which is one of the uses of the class
Python hash, XML, Configparser, Sheve, Shutil module explanation and object-oriented first knowledge