一、模塊、包
什么是模塊?
模塊實質上就是一個python文件,它是用來組織代碼的,意思就是說把python代碼寫到里面,文件名就是模塊的名稱,test.py test就是模塊名稱。
什么是包?
包,package本質就是一個文件夾,和文件夾不一樣的是它有一個__init__.py文件,包是從邏輯上來組織模塊的,也就是說它是用來存放模塊的,如果你想導入其他目錄下的模塊,那么這個目錄必須是一個包才可以導入。
導入模塊
1
2
3
4
5
|
import module #導入模塊
from module import * #導入該模塊中的所有方法,慎用
from module import fun as xx_fun #導入指定的方法,然后起別名
from module import fun1,fun2,fun3 #導入模塊下的多個方法
import module,實際上就是把該模塊的代碼賦值給模塊名,也就是module.py里面所有的代碼,賦值給了module這個變量,如果是from module import fun,就是把module打開,把module里面的fun方法拿過來使用
|
導入模塊的本質,就是把python文件拿過來執行一次。
使用包中的模塊需要在__init__.py文件中from . import xxx
模塊分類:
標准庫:python內置的
開源模塊:第三方
自定義模塊:自己寫的
二、os、sys模塊
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import os
print(os.getcwd())#取當前工作目錄
os.chmod("/usr/local",7)#給文件/目錄加權限
print(os.chdir("../"))#更改當前目錄
print(os.curdir)#當前目錄
print(os.pardir)#父目錄
print(os.makedirs("/usr/hehe/hehe1"))#遞歸創建文件夾,父目錄不存在時創建父目錄
print(os.removedirs("/usr/hehe/hehe1"))#遞歸刪除空目錄
print(os.mkdir("test1"))#創建文件夾
print(os.rmdir("test1"))#刪除指定的文件夾
print(os.remove("test"))#刪除文件
print(os.listdir('.'))#列出一個目錄下的所有文件
os.rename("test","test1")#重命名
print(os.stat("len_os.py"))#獲取文件信息
print(os.sep)#當前操作系統的路徑分隔符
print(os.linesep)#當前操作系統的換行符
print(os.pathsep)#當前系統的環境變量中每個路徑的分隔符,linux是:,windows是;
print(os.environ)#當前系統的環境變量
print(os.name)#當前系統名稱
print(os.path.abspath(__file__))#獲取絕對路徑
print(os.path.split("/usr/hehe/hehe.txt"))#分割路徑和文件名
print(os.path.dirname("/usr/local"))#獲取父目錄
print(os.path.basename("/usr/local"))#獲取最后一級,如果是文件顯示文件名,如果是目錄顯示目錄名
print(os.path.exists("/usr/local"))#目錄/文件是否存在
print(os.path.isabs("."))#判斷是否是絕對路徑
print(os.path.isfile("/usr/local"))#判斷是否是一個文件
print(os.path.isdir("/usr/local"))#是否是一個路徑
print(os.path.join("/root",'hehe','a.sql'))#拼接成一個路徑
print(os.path.getatime("len_os.py"))#輸出最近訪問時間
print(os.path.getmtime("len_os.py"))#輸出最近訪問時間
|
1
2
3
4
5
6
7
8
|
sys.argv 命令行參數List,第一個元素是程序本身路徑
sys.exit(n) 退出程序,正常退出時exit(0)
sys.version 獲取Python解釋程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform 返回操作系統平台名稱
sys.stdout.write('please:')#向屏幕輸出一句話
val = sys.stdin.readline()[:-1]#獲取輸入的值
|
三、random模塊
1
2
3
4
5
6
7
8
9
10
11
|
import random,string
print(random.random())#隨機浮點數,默認取0-1,不能指定范圍
print(random.randint(1,20))#隨機整數
print(random.randrange(1,20))#隨機產生一個range
print(random.choice('x23serw4'))#隨機取一個元素
print(random.sample('hello',2))#從序列中隨機取幾個元素
print(random.uniform(1,9))#隨機取浮點數,可以指定范圍
x = [1,2,3,4,6,7]
random.shuffle(x)#洗牌,打亂順序,會改變原list的值
print(x)
print(string.ascii_letters+string.digits)#所有的數字和字母
|
四、time&datetime模塊
time和datetime模塊主要用於操作時間
時間有三種表示方式,一種是時間戳、一種是格式化時間、一種是時間元組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import datetime,time
print(time.timezone)#和標准時間相差的時間,單位是s
print(time.time())#獲取當前時間戳
print(time.sleep(1))#休息幾s
print(time.gmtime())#把時間戳轉換成時間元組,如果不傳的話,默認取標准時區的時間戳
print(time.localtime())#把時間戳轉換成時間元組,如果不傳的話,默認取當前時區的時間戳
print(time.mktime(time.localtime()))#把時間元組轉換成時間戳
print(time.strftime("%y%m%d %H%M%S"))#將時間元組轉換成格式化輸出的字符串
print(time.strptime("20160204 191919","%Y%m%d %H%M%S"))#將格式化的時間轉換成時間元組
print(time.struct_time)#時間元組
print(time.asctime())#時間元轉換成格式化時間
print(time.ctime())#時間戳轉換成格式化時間
print(datetime.datetime.now())#當然時間格式化輸出
print(datetime.datetime.now()+datetime.timedelta(3))#3天后的時間
print(datetime.datetime.now()+datetime.timedelta(-3))#3天前的時間
|
五、shelve模塊
shelve模塊用來持久化存儲數據,比起json來,json只能存儲list、字典這樣的數據類型,如果是一個函數,一個類的話,就沒有辦法存儲了,但是shelve模塊可以,shelve模塊是key-value存儲的,value是你存儲的內容,使用如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import shelve
d = shelve.open('shelve_test') #打開一個文件
class Test(object):
def __init__(self,n):
self.n = n
t = Test(123)
t2 = Test(123334)
def func():
print('hello')
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t #持久化類
d["t2"] = t2
d["t3"] = func
print(d.get("t3"))#獲取內容
d.close()
|
六、hashlib模塊
hashlib模塊,主要用於加密相關的操作,在python3的版本里,代替了md5和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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進制格式hash
print(len(m.hexdigest())) #16進制格式hash
# ######## 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())
|
七、configparser模塊
configparser模塊用來操作配置文件,用於生成和修改常見配置文檔,python 3.x 中為configparser,python2中為ConfigParser。
一個常見的配置文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
|
如果想用python生成一個這樣的文檔怎么做呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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('example.ini', 'w') as configfile:
config.write(configfile)
|
下面是一些常用的操作,修改、添加、刪除節點、屬性
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import configparser
config = configparser.ConfigParser()
config.read('my.cnf')
sections = config.sections()#獲取所有節點
print(config.get('bitbucket.org','User'))#取對應節點下面key的值
config.add_section('NEW')#增加節點
config.set('NEW','test','true')#增加節點下面對應的熟悉和值
config.set('DEFAULT','niu','222222')#修改節點下的屬性
config.write(open("my.cnf","w"))#寫入修改后的文件
config.has_option('NEW','test')#節點下是否有對應的屬性
config.has_section('NEW')#是否有該節點
config.remove_section('NEW')#刪除節點
config.remove_option('NEW','test')#刪除節點下面的key
|
八、re模塊
re模塊是正則表達式模塊,用來匹配一些特定的字符串。
常用的正則表達式符號
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
'.' 默認匹配除\n之外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行
'^' 匹配字符開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$' 匹配字符結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*號前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 結果為['abb', 'ab', 'a']
'+' 匹配前一個字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb']
'?' 匹配前一個字符1次或0次
'{m}' 匹配前一個字符m次
'{n,m}' 匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC'
'(...)' 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c
'\A' 只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符結尾,同$
'\d' 匹配數字0-9
'\D' 匹配非數字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t'
|
常用的匹配語法
1
2
3
4
5
|
re.match 從頭開始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符當做列表分隔符
re.sub 匹配字符並替換
|