Python Foundation article-day6

Source: Internet
Author: User

This section introduces:

1. Module
1.1 Time Module
1.2 Random Module
1.3 Shutil Module
1.4 Shelve Module
1.5 XML Module
1.6 Configparser Module
1.7 Hashlib Module
1.8 Logging Module
1.9 Re Module

1. Module

1.1 Time Module

Time
Print (Time.clock ()) #返回处理器时间, 3.3 started obsolete, changed to Time.process_time () measurement processor operation time, not including sleep time, unstable, Mac on the test
Print (Time.altzone) #返回与utc时间的时间差, in seconds \
Print (Time.asctime ()) #返回时间格式 "Fri 19 11:14:16 2016",
The struct time object format for print (Time.localtime ()) #返回本地时间
Print (Time.gmtime (Time.time () -800000)) #返回utc时间的struc时间对象格式
Print (Time.asctime (Time.localtime ())) #返回时间格式 "Fri 19 11:14:16 2016",
Print (Time.ctime ()) #返回Fri 19 12:38:29 2016 format, ibid.
Date string converted to timestamp
String_2_struct = Time.strptime ("2016/05/22", "%y/%m/%d") #将 date string into a struct time object format
Print (string_2_struct)

Struct_2_stamp = Time.mktime (string_2_struct) #将struct时间对象转成时间戳
Print (Struct_2_stamp)

Convert timestamp to string format
Print (Time.gmtime (Time.time () -86640)) #将utc时间戳转换成struct_time格式
Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.gmtime ())) #将utc the struct_time format to the specified string format

time plus minus
import datetime
Print (Datetime.datetime.now ()) #返回 2016-08-19 12:47:03.941925
Print (Datetime.date.fromtimestamp (Time.time ()) # Timestamp goes directly to date format 2016-08-19
Print (Datetime.datetime.now ())
Print (Datetime.datetime.now () + Datetime.timedelta (3)) #当前时间 + 3 days
Print (Datetime.datetime.now () + Datetime.timedelta ( -3)) #当前时间-3 days
Print (Datetime.datetime.now () + Datetime.timedelta (hours=3)) #当前时间 + 3 hours
Print (Datetime.datetime.now () + Datetime.timedelta (minutes=30)) #当前时间 +30 min
C_time = Datetime.datetime.now ()
Print (C_time.replace (minute=3,hour=2)) #时间替换

1.2 Random Module
>>> Import Random
>>> print (Random.random ())
0.208189160969
>>> Print (Random.randint (1,5)) #随机打印1-5 data
5
>>> Print (Random.randrange (1,5)) #随机打印1-4
1
>>> Import String
>>> Str_source = string.ascii_letters + string.digits
>>> Print (Random.sample (str_source,7)) #随机打印str_source中的7个字符
[' s ', ' E ', ' w ', ' Z ', ' h ', ' I ', ' N ']

Generate random verification code >>:
Import Random
Checkcode = ' '
For I in range (4): #四位随机码
Current = Random.randrange (0,4) #思维随机码
If current! = I:
temp = Chr (Random.randint (65,90))
Else
temp = Random.randint (0,9)
Checkcode + = str (temp)
Print Checkcode

1.3 Shutil Module

Shutil.copyfileobj (FSRC, fdst[, length])
Copy the contents of the file to another file, which can be part of the content

Shutil.copyfile (SRC, DST)
Copy files

Shutil.copymode (SRC, DST)
Copy permissions only. Content, group, user are not changed

Shutil.copystat (SRC, DST)
Information on the status of the copy, including: mode bits, Atime, mtime, Flags

Shutil.copy (SRC, DST)
Copying files and Permissions

Shutil.copy2 (SRC, DST)
Copying files and status information

Shutil.ignore_patterns (*patterns)
Shutil.copytree (SRC, DST, Symlinks=false, Ignore=none)
Recursive de-Copying files

Shutil.rmtree (path[, ignore_errors[, OnError])
To delete a file recursively

Shutil.move (SRC, DST)
To move a file recursively

Shutil.make_archive (base_name, Format,...)

Create a compressed package and return the file path, for example: Zip, tar

      • Base_name: The file name of the compressed package, or the path to the compressed package. Only the file name is saved to the current directory, otherwise saved to the specified path,
        For example: www + = Save to Current path
        such as:/users/wupeiqi/www = Save to/users/wupeiqi/
      • Format: Compressed package type, "Zip", "tar", "Bztar", "Gztar"
      • Root_dir: Folder path to compress (default current directory)
      • Owner: User, default Current user
      • Group: Groups, default current group
      • Logger: Used to log logs, usually logging. Logger Object
Shutil Processing of compressed packets is done by calling the ZipFile and Tarfile two modules, in detail:
Import zipfile# Compression z = zipfile. ZipFile (' Laxi.zip ', ' W ') z.write (' A.log ') z.write (' Data.data ') Z.close () # Unzip z = zipfile. ZipFile (' Laxi.zip ', ' R ') Z.extractall () Z.close ()
--------------------------------------
# Compress tar = Tarfile.open (' Your.tar ', ' W ') tar.add ('/users/wupeiqi/pycharmprojects/bbs2.zip ', arcname= ' Bbs2.zip ') Tar.add ('/users/wupeiqi/pycharmprojects/cmdb.zip ', arcname= ' Cmdb.zip ') Tar.close () # Unzip tar = Tarfile.open (' Your.tar ') , ' R ') Tar.extractall ()  # can set decompression address tar.close ()
-------------------------------------
# shutil.copyfile ("time-datetime.py", "Timeeme")  #拷贝文件
# shutil.copy2 ("time-datetime.py", "Time_bak.txt") #拷贝文件和状态信息
# Shutil.copytree (r "D:\python training \our_python\day3", ' Day3_bak ') #递归的去拷贝文件
# shutil.rmtree (' Day3_bak ') #递归的去删除文件
# shutil.move (' Day3_bak ', ' DAY3_BAK2 ') #移动文件

1.4 Shelve Module

The shelve module is a simple k,v module that persists memory data through a file and can persist any Python data format that pickle can support

Save data:

Import shelve
D = Shelve.open (' shelve_test ')

#存函数
def stu_date (name,age):
Print ("Std", name,age)
#列表
name = [' Zs ', ' ls ', ' we ']
#字典
data = {' name ': ' Zs ', ' age ': ' 22 '}

#存储
D[' func '] = stu_date
d[' lis '] = name
d[' dic '] = data

Read data:

Import  Shelve
def stu_date (name,age):
Print ("Std", name,age)

f = shelve.open (' shelve_test ')

Print (f[' func '] (' Zhangsong ', 23))
Print (f[' lis ')
Print (f[' dic ')

1.5 XML Module

To create an XML file:

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) # Generate Document Object
Et.write ("Test.xml", encoding= "Utf-8", Xml_declaration=true)

Et.dump (new_xml) # Print generated format

To delete an XML file:

Import Xml.etree.ElementTree as ET

Tree = Et.parse ("Xml_test.xml")
root = Tree.getroot ()

For country in Root.findall (' Country '):
rank = Int (country.find (' rank '). Text)
If rank > 50:
Root.remove (Country)

Tree.write (' Output.xml ')

To modify an XML file:

Import Xml.etree.ElementTree as ET

Tree = Et.parse ("Xml_test_bak.xml")
root = Tree.getroot ()


# Modify First read all the files into memory, and then use the loop to take out the data, modify the data to save the data as other files or save back the original file
For node in Root.iter (' year '):
# Print (Node,type (node))
# Print (Node,type (node.text))
new_year = Int (node.text) + 1
Node.text = str (new_year)
Node.set ("Updated", "yes")

Tree.write ("Xml_test_bak.xml")

Read the XML file:

Import Xml.etree.ElementTree as ET

Tree = Et.parse ("Xml_test.xml")
root = Tree.getroot ()
Print (Root.tag)

# Traverse XML Document
# for child in Root:
# Print (Child.tag, child.attrib)
# for I in the child :
# print (' \ t ', I.tag, I.text)
#

# traverse the year in an XML document
# for child in Root:
# #print (Child.tag, Child.attrib)
# for i in Child.iter (' year '):
# print (' \ t ', I.tag, I.text)

# # Traverse only the year node
# for node in Root.iter (' year '):
# Print (Node.tag, node.text)

1.6 Configparser Module

To create a file:

Import Configparser

Config = Configparser. Configparser ()
config["DEFAULT"] = {' Serveraliveinterval ': ' 45 ',
' Compression ': ' Yes ',
' CompressionLevel ': ' 9 '}

config[' bitbucket.org ' = {}
config[' bitbucket.org ' [' User '] = ' HG '
config[' topsecret.server.com ' = {}
Topsecret = config[' topsecret.server.com ']
topsecret[' Host Port ' = ' 50022 ' # mutates the parser
topsecret[' ForwardX11 ' = ' no ' # same here
config[' DEFAULT ' [' ForwardX11 '] = ' yes '
With open (' Config.ini ', ' W ') as ConfigFile:
Config.write (ConfigFile)

Read the file:

Import Configparser
Config = Configparser. Configparser ()
# Print (Config.sections ())
Config.read (' Config.ini ')
Print (Config.sections ())
# print (' bitbucket.org ' in config)
Print (config[' bitbucket.org ' [' User '])
Print (config[' DEFAULT ' [' Compression '])
Topsecret = config[' topsecret.server.com ']
Print (topsecret[' host Port ')

Print ("Loop". Center (20, '-'))
For k in config[' bitbucket.org ': #读取指定域和DEFAULT域的key
Print (k)

File operation:

Import Configparser

Config = Configparser. Configparser ()
Config.read (' Config.ini ')

# ########## Read ##########
# secs = Config.sections ()
# print secs
# options = config.options (' group2 ')
# Print Options

# item_list = Config.items (' group2 ')
# Print Item_list

# val = config.get (' group1 ', ' key ')
# val = config.getint (' group1 ', ' key ')

# ########## Rewrite ##########
# sec = config.remove_section (' group1 ')
# config.write (Open (' I.cfg ', "w"))

# sec = config.has_section (' Wupeiqi ')
# sec = config.add_section (' Wupeiqi ')
# config.write (Open (' I.cfg ', "w"))


# config.set (' group2 ', ' K1 ', 11111)
# config.write (Open (' I.cfg ', "w"))

# config.remove_option (' group2 ', ' age ')
# config.write (Open (' I.cfg ', "w"))

1.7 Hashlib Module

Import Hashlib

m = Hashlib.md5 ()
M.update (b "Hello")
M.update (b "It ' s Me")
#print (M.digest ())
M.update (b "It ' s been a long time since last time we ...")

#print (M.digest ()) # 2 binary format hash
#print (Len (M.hexdigest ())) # 16 binary format hash
‘‘‘
def digest (self, *args, **kwargs): # Real Signature Unknown
"" "Return the Digest value as a string of binary data." "
Pass

def hexdigest (self, *args, **kwargs): # Real Signature Unknown
"" "Return the Digest value as a string of hexadecimal digits." "" "
Pass

‘‘‘
Import Hashlib

# ######## MD5 ########

hash = HASHLIB.MD5 ()
Hash.update (b ' admin ')
Print ("MD5")
Print (Hash.hexdigest ())

# ######## SHA1 ########

hash = HASHLIB.SHA1 ()
Hash.update (b ' admin ')
Print ("SH1")
Print (Hash.hexdigest ())

# ######## sha256 ########

hash = hashlib.sha256 ()
Hash.update (b ' admin ')
Print ("sh256")
Print (Hash.hexdigest ())

# ######## sha384 ########

hash = hashlib.sha384 ()
Hash.update (b ' admin ')
Print ("sh384")
Print (Hash.hexdigest ())

# ######## sha512 ########

hash = hashlib.sha512 ()
Hash.update (b ' admin ')
Print ("sh512")
Print (Hash.hexdigest ())

1.8 Logging Module

Specify the log level:

Import logging

#日志输出到文件并指定日志级别
#logging. Basicconfig (filename= ' Test.log ', level=logging.info)

#为日志加上时间
Logging.basicconfig (format= '% (asctime) s% (filename) s-% (Lineno) d% (levelname) s:% (message) s ', datefmt= '%m/%d/%y%i:% m:%s%p ')

Logging.debug ("User [Alex] attempted wrong password more than 1 times")
Logging.info ("User [Alex] attempted wrong password more than 2 times")
Logging.warning ("User [Alex] attempted wrong password more than 3 times")
Logging.critical ("Server is Down")

Different levels of log output:

Import logging

# Create Logger
Logger = Logging.getlogger (' Test-log ')
Logger.setlevel (logging. DEBUG)

# Create console handler and set level to debug
ch = logging. Streamhandler ()
Ch.setlevel (Logging.info)

# Create file handler and set level to warning
FH = logging. Filehandler ("Access.log")
Fh.setlevel (logging. ERROR)
# Create Formatter
Ch_formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
Fh_formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')

# Add formatter to CH and FH
Ch.setformatter (Ch_formatter)
Fh.setformatter (Fh_formatter)

# Add CH and FH to Logger
Logger.addhandler (CH)
Logger.addhandler (FH)

# ' Application ' code
Logger.debug (' Debug message ')
Logger.info (' info message ')
Logger.warn (' Warn message ')
Logger.error (' Error message ')
Logger.critical (' critical message ')

Python Foundation article-day6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.