日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python自动化常用模块_Python自动化 【第五篇】:Python基础-常用模块

發(fā)布時間:2024/4/11 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python自动化常用模块_Python自动化 【第五篇】:Python基础-常用模块 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

目錄

模塊介紹

time和datetime模塊

random

os

sys

shutil

json和pickle

shelve

xml處理

yaml處理

configparser

hashlib

re正則表達(dá)式

1. ? ? ?模塊介紹

1.1??? 定義

能夠?qū)崿F(xiàn)某個功能的代碼集合(本質(zhì)是py文件)? test.p的模塊名是test包的定義:用來從邏輯上組織模塊,本質(zhì)就是一個目錄(必須帶有一個__init__.py文件)

1.2??? 導(dǎo)入方法

a)?Import module

b)?Import module1,module2

c)?From module import *

d)?From module import m1,m2,m3

e) From module import logger as module_logger

1.3??? Import 本質(zhì)

導(dǎo)入模塊的本質(zhì)就是把python文件解釋一遍

導(dǎo)入包的本質(zhì)就是在執(zhí)行該包下的__init__.py文件

1.4??? 導(dǎo)入優(yōu)化

From module import test as module_test

1.5??? 模塊的分類

a)?標(biāo)準(zhǔn)庫

b)?開源模塊(第三方模塊)

c)?自定義模塊

2. ? ? ?time & datetime模塊

time的三種表現(xiàn)方式:

1)時間戳(用秒來表示)

2)格式化的時間字符串

3)元組(struct_time)共九個元素。

2.1??? 時間戳

1 1 importtime2

3 2 #print(time.clock()) #返回處理器時間,3.3開始已廢棄 , 改成了time.process_time()測量處理器運(yùn)算時間,不包括sleep時間,不穩(wěn)定,mac上測不出來

4

5 3 #print(time.altzone) #返回與utc時間的時間差,以秒計(jì)算\

6

7 4 #print(time.asctime()) #返回時間格式"Fri Aug 19 11:14:16 2016",

8

9 5 #print(time.localtime()) #返回本地時間 的struct time對象格式

10

11 6 #print(time.gmtime(time.time()-800000)) #返回utc時間的struc時間對象格式

12

13 7

14

15 8 #print(time.asctime(time.localtime())) #返回時間格式"Fri Aug 19 11:14:16 2016",

16

17 9 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上

18

19 10

20

21 11 #日期字符串 轉(zhuǎn)成 時間戳

22

23 12 #string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #將 日期字符串 轉(zhuǎn)成 struct時間對象格式

24

25 13 #print(string_2_struct)

26

27 14 #struct_2_stamp = time.mktime(string_2_struct) #將struct時間對象轉(zhuǎn)成時間戳

28

29 15 #print(struct_2_stamp)

30

31 16 #將時間戳轉(zhuǎn)為字符串格式

32

33 17 #print(time.gmtime(time.time()-86640)) #將utc時間戳轉(zhuǎn)換成struct_time格式

34

35 18 #print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #將utc struct_time格式轉(zhuǎn)成指定的字符串格式

36

37 19 #時間加減

38

39 20 importdatetime40

41 21 #print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925

42

43 22 #print(datetime.date.fromtimestamp(time.time()) ) # 時間戳直接轉(zhuǎn)成日期格式 2016-08-19

44

45 23 #print(datetime.datetime.now() )

46

47 24 #print(datetime.datetime.now() + datetime.timedelta(3)) #當(dāng)前時間+3天

48

49 25 #print(datetime.datetime.now() + datetime.timedelta(-3)) #當(dāng)前時間-3天

50

51 26 #print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當(dāng)前時間+3小時

52

53 27 #print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當(dāng)前時間+30分

54

55 28 #c_time = datetime.datetime.now()

56

57 29 #print(c_time.replace(minute=3,hour=2)) #時間替換

View Code

2.2 ? ?格式化的時間字符串

格式參照:

%a????本地(locale)簡化星期名稱

%A????本地完整星期名稱

%b????本地簡化月份名稱

%B????本地完整月份名稱

%c????本地相應(yīng)的日期和時間表示

%d????一個月中的第幾天(01?-?31)

%H????一天中的第幾個小時(24小時制,00?-?23)

%I????第幾個小時(12小時制,01?-?12)

%j????一年中的第幾天(001?-?366)

%m????月份(01?-?12)

%M????分鐘數(shù)(00?-?59)

%p????本地am或者pm的相應(yīng)符????一

%S????秒(01?-?61)????二

%U????一年中的星期數(shù)。(00?-?53星期天是一個星期的開始。)第一個星期天之前的所有天數(shù)都放在第0周。????三

%w????一個星期中的第幾天(0?-?6,0是星期天)????三

%W????和%U基本相同,不同的是%W以星期一為一個星期的開始。

%x????本地相應(yīng)日期

%X????本地相應(yīng)時間

%y????去掉世紀(jì)的年份(00?-?99)

%Y????完整的年份

%Z????時區(qū)的名字(如果不存在為空字符)

%%????‘%’字符

2.3??? 時間關(guān)系轉(zhuǎn)換

3. ? ? random模塊

3.1??? 隨機(jī)數(shù)

importrandomprint (random.random()) #0.6445010863311293

#random.random()用于生成一個0到1的隨機(jī)符點(diǎn)數(shù): 0 <= n < 1.0

print (random.randint(1,7)) #4

#random.randint()的函數(shù)原型為:random.randint(a, b),用于生成一個指定范圍內(nèi)的整數(shù)。

#其中參數(shù)a是下限,參數(shù)b是上限,生成的隨機(jī)數(shù)n: a <= n <= b

print (random.randrange(1,10)) #5

#random.randrange的函數(shù)原型為:random.randrange([start], stop[, step]),

#從指定范圍內(nèi),按指定基數(shù)遞增的集合中 獲取一個隨機(jī)數(shù)。如:random.randrange(10, 100, 2),

#結(jié)果相當(dāng)于從[10, 12, 14, 16, ... 96, 98]序列中獲取一個隨機(jī)數(shù)。

#random.randrange(10, 100, 2)在結(jié)果上與 random.choice(range(10, 100, 2) 等效。

print(random.choice('liukuni')) #i

#random.choice從序列中獲取一個隨機(jī)元素。

#其函數(shù)原型為:random.choice(sequence)。參數(shù)sequence表示一個有序類型。

#這里要說明一下:sequence在python不是一種特定的類型,而是泛指一系列的類型。

#list, tuple, 字符串都屬于sequence。有關(guān)sequence可以查看python手冊數(shù)據(jù)模型這一章。

#下面是使用choice的一些例子:

print(random.choice("學(xué)習(xí)Python"))#學(xué)

print(random.choice(["JGood","is","a","handsome","boy"])) #List

print(random.choice(("Tuple","List","Dict"))) #List

print(random.sample([1,2,3,4,5],3)) #[1, 2, 5]

#random.sample的函數(shù)原型為:random.sample(sequence, k),從指定序列中隨機(jī)獲取指定長度的片斷。sample函數(shù)不會修改原有序列。

View Code

3.2??? 實(shí)際應(yīng)用

#!/usr/bin/env python

#encoding: utf-8

importrandomimportstring#隨機(jī)整數(shù):

print(random.randint(0, 99)) #70

#隨機(jī)選取0到100間的偶數(shù):

print(random.randrange(0, 101, 2)) #4

#隨機(jī)浮點(diǎn)數(shù):

print(random.random()) #0.2746445568079129

print(random.uniform(1, 10)) #9.887001463194844

#隨機(jī)字符:

print(random.choice('abcdefg%^*f')) #f

#多個字符中選取特定數(shù)量的字符:

print(random.sample('abcdefghij', 3)) #['f', 'h', 'd']

#隨機(jī)選取字符串:

print(random.choice(['apple', 'pear', 'peach', 'orange', 'lemon'])) #apple

#洗牌#

items= [1, 2, 3, 4, 5, 6, 7]print(items) #[1, 2, 3, 4, 5, 6, 7]

random.shuffle(items)print(items) #[1, 4, 7, 2, 5, 3, 6]

View Code

3.3??? 生成隨機(jī)驗(yàn)證碼

importrandom

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

View Code

4. ? ? ?os模塊

os.getcwd() 獲取當(dāng)前工作目錄,即當(dāng)前python腳本工作的目錄路徑

os.chdir("dirname")? 改變當(dāng)前腳本工作目錄;相當(dāng)于shell下cd

os.curdir? 返回當(dāng)前目錄: ('.')

os.pardir? 獲取當(dāng)前目錄的父目錄字符串名:('..')

os.makedirs('dirname1/dirname2')??? 可生成多層遞歸目錄

os.removedirs('dirname1')??? 若目錄為空,則刪除,并遞歸到上一級目錄,如若也為空,則刪除,依此類推

os.mkdir('dirname')??? 生成單級目錄;相當(dāng)于shell中mkdir dirname

os.rmdir('dirname')??? 刪除單級空目錄,若目錄不為空則無法刪除,報(bào)錯;相當(dāng)于shell中rmdir dirname

os.listdir('dirname')??? 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印

os.remove()? 刪除一個文件

os.rename("oldname","newname")? 重命名文件/目錄

os.stat('path/filename')? 獲取文件/目錄信息

os.sep??? 輸出操作系統(tǒng)特定的路徑分隔符,win下為"\\",Linux下為"/"

os.linesep??? 輸出當(dāng)前平臺使用的行終止符,win下為"\r\n",Linux下為"\n"

os.pathsep??? 輸出用于分割文件路徑的字符串

os.name??? 輸出字符串指示當(dāng)前使用平臺。win->'nt';

Linux->'posix'

os.system("bash

command")? 運(yùn)行shell命令,直接顯示

os.environ? 獲取系統(tǒng)環(huán)境變量

os.path.abspath(path)? 返回path規(guī)范化的絕對路徑

os.path.split(path)? 將path分割成目錄和文件名二元組返回

os.path.dirname(path)? 返回path的目錄。其實(shí)就是os.path.split(path)的第一個元素

os.path.basename(path)? 返回path最后的文件名。如何path以/或\結(jié)尾,那么就會返回空值。即os.path.split(path)的第二個元素

os.path.exists(path)? 如果path存在,返回True;如果path不存在,返回False

os.path.isabs(path)? 如果path是絕對路徑,返回True

os.path.isfile(path)? 如果path是一個存在的文件,返回True。否則返回False

os.path.isdir(path)? 如果path是一個存在的目錄,則返回True。否則返回False

os.path.join(path1[, path2[, ...]])? 將多個路徑組合后返回,第一個絕對路徑之前的參數(shù)將被忽略

os.path.getatime(path)? 返回path所指向的文件或者目錄的最后存取時間

os.path.getmtime(path)? 返回path所指向的文件或者目錄的最后修改時間

5. ? ? ?sys模塊

sys.argv ? ? ? ? ? ?命令行參數(shù)List,第一個元素是程序本身路徑

sys.exit(n) ? ? ? ? 退出程序,正常退出時exit(0)

sys.version??????? 獲取Python解釋程序的版本信息

sys.maxint???????? 最大的Int值

sys.path ? ? ? ? ? ?返回模塊的搜索路徑,初始化時使用PYTHONPATH環(huán)境變量的值

sys.platform?????? 返回操作系統(tǒng)平臺名稱

sys.stdout.write('please:')

val = sys.stdin.readline()[:-1]

6. ? ? ?shutil模塊

importshutil

f1= open("file.txt", encoding="utf-8")

f2= open("file2.txt", "w",encoding="utf-8")

shutil.copyfileobj(f1,f2)

View Code

shutil.copyfile() 輸入源文件就copy:

shutil.copyfile("file1", "file2")

View Code

shutil.copymode() 僅拷貝權(quán)限,內(nèi)容、組、用戶均不變(待實(shí)驗(yàn))

shutil.copystat() 拷貝權(quán)限,沒有創(chuàng)建新文件

shutil.copy() 拷貝文件

shutil.copy2() 所有都拷貝(文件和狀態(tài)信息)

shutil.copytree() 遞歸拷貝文件(將文件和所在目錄都拷貝)

shutil.copytree("test1", "test2")

View Code

shutil.rmtree() 遞歸刪除文件? 比調(diào)用shell命令高效

shutil.rmtree("test3")

View Code

shutil.move() 遞歸的移動文件

shutil.make_archive(base_name, format, file)

importshutil

shutil.make_archive("shutil_archive_test", "zip", "E:\Pycharm\day5")

View Code

zipfile

importzipfile

z= zipfile.ZipFile("file1.zip", "w") #指定壓縮后的文件名是file1.txt

z.write("test1.py") #先把test1.py壓縮至file1.zip

print("----------") #可以干些其他事

z.write("test2.py") #然后把test2.py壓縮至file1.zip

z.close()

View Code

7. ? ? ?json和pickle模塊

解決了不同語言不同平臺的之間的數(shù)據(jù)交換

8. ? ? ?shelve模塊

shelve模塊是一個簡單的k,v將內(nèi)存數(shù)據(jù)通過文件持久化的模塊,可以持久化任何pickle可支持的python數(shù)據(jù)格式。

importshelveimportdatetime

d= shelve.open('shelve_test') #打開一個文件

#info = {"age":22,"job":"it"}#

#name = ["alex", "rain", "test"]#d["name"] = name # 持久化列表#d["info"] = info # 持久化類#d["date"] =datetime.datetime.now()#d.close()

print(d.get("name"))print(d.get("info"))print(d.get("date"))

View Code

9. ? ? ?xml處理模塊

xml的格式如下,就是通過<>節(jié)點(diǎn)來區(qū)別數(shù)據(jù)結(jié)構(gòu)的:

2

2008

141100

5

2011

59900

69

2011

13600

View Code

xml協(xié)議在各個語言里的都是支持的,在python中可以用以下模塊操作xml

importxml.etree.ElementTree as ET

tree= ET.parse("xmltest.xml")

root=tree.getroot()print(root.tag)#遍歷xml文檔

for child inroot:print(child.tag, child.attrib)for i inchild:print(i.tag, i.text, i.attrib)#只遍歷year 節(jié)點(diǎn)

for node in root.iter('year'):print(node.tag, node.text)

修改和刪除xml文檔內(nèi)import xml.etree.ElementTree as ET

tree= ET.parse("xmltest.xml")

root=tree.getroot()#修改

for node in root.iter('year'):

new_year= int(node.text) + 1node.text=str(new_year)

node.set("updated", "yes")

tree.write("xmltest.xml")#刪除node

for country in root.findall('country'):

rank= int(country.find('rank').text)if rank > 50:

root.remove(country)

tree.write('output.xml')

View Code

自己創(chuàng)建xml文檔

importxml.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")

age.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)#打印生成的格式

View Code

10. ? ? PyYAML模塊

yaml語法(用作配置文件)

數(shù)據(jù)結(jié)構(gòu)可以用類似大綱的縮排方式呈現(xiàn),結(jié)構(gòu)通過縮進(jìn)來表示,連續(xù)的項(xiàng)目通過減號“-”來表示,map結(jié)構(gòu)里面的key/value對用冒號“:”來分隔。樣例如下:

house:

family:

name: Doe

parents:-John-Jane

children:-Paul-Mark-Simone

address:

number:34street: Main Street

city: Nowheretown

zipcode:12345

View Code

11. ? ? ?ComfigParser模塊

用于生成和修改常見配置文檔,當(dāng)前模塊的名稱在 python 3.x 版本中變更為 configparser。

格式如下:

[DEFAULT]

ServerAliveInterval= 45Compression=yes

CompressionLevel= 9ForwardX11=yes

[bitbucket.org]

User=hg

[topsecret.server.com]

Port= 50022ForwardX11= no

View Code

用python生成一個這樣的文檔

importconfigparser

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('example.ini', 'w') as configfile:

config.write(configfile)

View Code

寫完后還可以讀出來:

>>> importconfigparser>>> config =configparser.ConfigParser()>>>config.sections()

[]>>> config.read('example.ini')

['example.ini']>>>config.sections()

['bitbucket.org', 'topsecret.server.com']>>> 'bitbucket.org' inconfig

True>>> 'bytebong.com' inconfig

False>>> config['bitbucket.org']['User']'hg'

>>> config['DEFAULT']['Compression']'yes'

>>> topsecret = config['topsecret.server.com']>>> topsecret['ForwardX11']'no'

>>> topsecret['Port']'50022'

>>> for key in config['bitbucket.org']: print(key)

...

user

compressionlevel

serveraliveinterval

compression

forwardx11>>> config['bitbucket.org']['ForwardX11']'yes'

View Code

configparser增刪改查語法

[section1]

k1=v1

k2:v2

[section2]

k1=v1importConfigParser

config=ConfigParser.ConfigParser()

config.read('i.cfg')########### 讀 ###########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')

########### 改寫 ###########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"))

View Code

12. ? ? ?hashlib模塊

用于加密相關(guān)的操作,3.x里代替了md5模塊和sha模塊,主要提供?SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

importhashlib

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進(jìn)制格式hash

print(len(m.hexdigest())) #16進(jìn)制格式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'''

importhashlib######### md5 ########

hash=hashlib.md5()

hash.update('admin')print(hash.hexdigest())######### sha1 ########

hash=hashlib.sha1()

hash.update('admin')print(hash.hexdigest())######### sha256 ########

hash=hashlib.sha256()

hash.update('admin')print(hash.hexdigest())######### sha384 ########

hash=hashlib.sha384()

hash.update('admin')print(hash.hexdigest())######### sha512 ########

hash=hashlib.sha512()

hash.update('admin')print(hash.hexdigest())

View Code

python 還有一個 hmac 模塊,它內(nèi)部對我們創(chuàng)建 key 和 內(nèi)容 再進(jìn)行處理然后再加密

importhmac

h= hmac.new('wueiqi')

h.update('hellowo')print h.hexdigest()

View Code

13. ? ? ?re模塊

常用正則表達(dá)式符號:

'.' ? ? ? ?默認(rèn)匹配除\n之外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行

'^' ? ? ? 匹配字符開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)

'$' ? ? ? 匹配字符結(jié)尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以

'*' ? ? ? 匹配*號前的字符0次或多次,re.findall("ab*","cabb3abcbbac")? 結(jié)果為['abb',?'ab',?'a']

'+' ? ? ? 匹配前一個字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 結(jié)果['ab',?'abb']

'?' ? ? ? ?匹配前一個字符1次或0次

'{m}' ? ?匹配前一個字符m次

'{n,m}'?匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結(jié)果'abb',?'ab',?'abb']

'|' ? ? ? ? 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結(jié)果'ABC'

'(...)' ? ? 分組匹配,re.search("(abc){2}a(123|456)c",?"abcabca456c").group() 結(jié)果 abcabca456c

'\A'????只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的

'\Z'????匹配字符結(jié)尾,同$

'\d'????匹配數(shù)字0-9

'\D'????匹配非數(shù)字

'\w'????匹配[A-Za-z0-9]

'\W' ? 匹配非[A-Za-z0-9]

's' ? ? ?匹配空白字符,\t、\n、\r , re.search("\s+","ab\tc1\n3").group(),結(jié)果?'\t'

'(?P...)'?分組匹配,re.search("(?P[0-9]{4})(?P[0-9]{2})(?P[0-9]{4})","371481199306143242").groupdict("city"),結(jié)果{'province':?'3714',?'city':?'81',?'birthday':?'1993'}

最常用的匹配語法

re.match 從頭開始匹配

re.search 匹配包含

re.findall 把所有匹配到的字符放到以列表中的元素返回

re.splitall 以匹配到的字符當(dāng)做列表分隔符

re.sub????? 匹配字符并替換

幾個匹配模式

re.I(re.IGNORECASE): 忽略大小寫(括號內(nèi)是完整寫法,下同)

M(MULTILINE): 多行模式,改變'^'和'$'的行為

S(DOTALL): 點(diǎn)任意匹配模式,改變'.'的行為

超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生

總結(jié)

以上是生活随笔為你收集整理的python自动化常用模块_Python自动化 【第五篇】:Python基础-常用模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。