7.python經常使用模塊

time模塊

經常使用表示時間方式: 時間戳,格式化的時間字符串,元組(struct_time)html

UTC(Coordinated Universal Time,世界協調時)亦即格林威治天文時間,世界標準時間。在中國爲UTC+8。DST(Daylight Saving Time)即夏令時。python

時間戳(timestamp)的方式:一般來講,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。web

元組(struct_time)方式:struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。算法

 


1. 時間戳轉換成struct_time

複製代碼
>>> import time
>>> time.time()
1513821691.159022
>>> time.gmtime()     # 轉換的是UTC時間
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=2, tm_min=1, tm_sec=40, tm_wday=3, tm_yday=355, tm_isdst=0)
>>> x = time.localtime()       #轉換的是本地時間(UTC+8)
>>> print(x)
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=10, tm_min=1, tm_sec=49, tm_wday=3, tm_yday=355, tm_isdst=0)

tm_wday(0-6)   星期一是0,星期天是6
複製代碼

2. struct_time轉換成時間戳

>>> time.mktime(x)        #x = time.localtime()
1513821709.0

3.struct_time轉換成format_time

複製代碼
%a    本地(locale)簡化星期名稱
%A    本地完整星期名稱
%b    本地簡化月份名稱
%B    本地完整月份名稱
%c    本地相應的日期和時間表示
%d    一個月中的第幾天(01 - 31%H    一天中的第幾個小時(24小時制,00 - 23%I    第幾個小時(12小時制,01 - 12%j    一年中的第幾天(001 - 366%m    月份(01 - 12%M    分鐘數(00 - 59%p    本地am或者pm的相應符    一
%S    秒(01 - 61)    二
%U    一年中的星期數。(00 - 53星期天是一個星期的開始。)第一個星期天以前的全部天數都放在第0周。
%w    一個星期中的第幾天(0 - 6,0是星期天)    三
%W    和%U基本相同,不一樣的是%W以星期一爲一個星期的開始。
%x    本地相應日期
%X    本地相應時間
%y    去掉世紀的年份(00 - 99%Y    完整的年份
%Z    時區的名字(若是不存在爲空字符)
%%    ‘%’字符
複製代碼
複製代碼
>>> import time
>>> time.time()
1513822266.5659332
>>> x = time.localtime()
>>> print(x)
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=10, tm_min=11, tm_sec=31, tm_wday=3, tm_yday=355, tm_isdst=0)
>>>
>>> time.strftime("%Y%m%d %H:%M:%S",x)
'20171221 10:11:31'
>>>

#語法:
#strftime(format,[tuple])
複製代碼

4 format_time轉換成struct_time

複製代碼
>>> time.strftime("%Y%m%d %H:%M:%S",x)
'20171221 10:11:31'
>>>
>>>
>>> time.ct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=10, tm_min=11, tm_sec=31, tm_wday=3, tm_yday=355, tm_isdst=-1)
用法:
strp('string',format
複製代碼

5.結構化時間轉換成字符串時間

複製代碼
import time
x = time.localtime()
print(x)
print(time.asctime(x))

結果:
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=10, tm_min=29, tm_sec=58, tm_wday=3, tm_yday=355, tm_isdst=0)

Thu Dec 21 10:29:58 2017
複製代碼

6.時間戳轉換成字符串

複製代碼
>>> import time
>>> time.time()
1513823679.9577746
>>> print(time.ctime())
Thu Dec 21 10:34:50 2017
複製代碼

random模塊

複製代碼
>>> import random
>>> random.random()    # 0~1 隨機浮點數
0.6990063739837862
>>> random.randint(1,7)   #隨機整數1~7
5
>>> random.randrange(1,7)   #隨機整數,不包括7
4
>>> random.choice('hello world')   #獲取一個隨機元素
'l'
>>> random.choice(['1','2','3',])
'2'

>>> random.sample([1,2,3,4,5],3)
[1, 2, 4]
random.sample的函數原型爲:random.sample(sequence, k),從指定
序列中隨機獲取指定長度的片
複製代碼

隨機驗證碼shell

複製代碼
import random
def v_code():
    code = ""
    for i in range(4):
        num = random.randint(0,9)             #隨機選擇0~9
        A1Z1 = chr(random.randint(65,90))     #隨機選擇A~Z
        a1z1 = chr(random.randint(97,122))    #隨機選擇a~z
        add = random.choice([num,A1Z1,a1z1])  #隨機選擇其中一個
        code = "".join([code,str(add)])       #拼接一次選到的元素
    return code                               #返回驗證碼#
print(v_code())

結果:
5adc
複製代碼

OS模塊

複製代碼
os.getcwd() #獲取當前工做目錄,即當前python腳本工做的目錄路徑

os.chdir()  #當前目錄

os.chdir("dirname")  #改變當前腳本工做目錄;至關於shell下cd    os.chdir(r"c:\Users")
os.curdir #返回當前目錄: ('.'),至關於shell下cd. os.pardir # 獲取當前目錄的父目錄字符串名:('..'),至關於shell下cd.. 返回上一層目錄 os.makedirs('dirname1/dirname2') #可生成多層遞歸目錄 os.makedirs(r"c:\a\b\c") os.removedirs('dirname1') #若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推 os.removedirs(r"c:\a\b\c") os.mkdir('dirname') #生成單級目錄;至關於shell中mkdir dirname os.rmdir('dirname') # 刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname os.listdir('dirname') #列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印 os.listdir("c:\\test") os.remove() #刪除一個文件 os.remove(r"c:\oldboy.txt") os.rename("oldname","newname") #重命名文件/目錄 os.rename("c:\\test","c:\\test2") os.stat('path/filename') # 獲取文件/目錄信息 os.stat("c:\\test2") os.sep #輸出操做系統特定的路徑分隔符,win下爲"\\",Linux下爲"/" os.linesep #輸出當前平臺使用的行終止符,win下爲"\r\n",Linux下爲"\n" os.pathsep #輸出用於分割文件路徑的字符串 os.name #輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix' os.system("bash command") #運行shell命令,直接顯示 os.environ #獲取系統環境變量 os.path.abspath(path) #返回path規範化的絕對路徑 os.path.split(path) #將path分割成目錄和文件名二元組返回 os.path.dirname(path) #返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path) # 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即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[, ...]]) #將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略 os.path.getatime(path) #返回path所指向的文件或者目錄的最後存取時間 os.path.getmtime(path) #返回path所指向的文件或者目錄的最後修改時間 os.path.getsize(path) #返回path的大小
複製代碼

sys模塊

複製代碼
sys.argv           命令行參數List,第一個元素是程序自己路徑
sys.exit(n)        退出程序,正常退出時exit(0)
sys.version        獲取Python解釋程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform       返回操做系統平臺名稱
複製代碼

shutil模塊

高級的 文件、文件夾、壓縮包 處理模塊編程

shutil.copy(src, dst)
拷貝文件和權限
json

1 import shutil
2
3 shutil.copy('f1.log', 'f2.log')

shutil.copy2(src, dst)
拷貝文件和狀態信息bash

shutil.copystat(src, dst)
僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags網絡

shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變dom

shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾

shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件

參考博客: http://www.cnblogs.com/linhaifeng/articles/6384466.html

Json和pickle模塊

什麼是序列化?

咱們把對象(變量)從內存中變成可存儲或傳輸的過程稱之爲序列化

爲何要序列化?

1:持久保存狀態

需知一個軟件/程序的執行就在處理一系列狀態的變化,在編程語言中,'狀態'會以各類各樣有結構的數據類型(也可簡單的理解爲變量)的形式被保存在內存中。

內存是沒法永久保存數據的,當程序運行了一段時間,咱們斷電或者重啓程序,內存中關於這個程序的以前一段時間的數據(有結構)都被清空了。

在斷電或重啓程序以前將程序當前內存中全部的數據都保存下來(保存到文件中),以便於下次程序執行可以從文件中載入以前的數據,而後繼續執行,這就是序列化。

具體的來講,你玩使命召喚闖到了第13關,你保存遊戲狀態,關機走人,下次再玩,還能從上次的位置開始繼續闖關。或如,虛擬機狀態的掛起等。

2:跨平臺數據交互

序列化以後,不只能夠把序列化後的內容寫入磁盤,還能夠經過網絡傳輸到別的機器上,若是收發的雙方約定好實用一種序列化的格式,那麼便打破了平臺/語言差別化帶來的限制,實現了跨平臺數據交互。

反過來,把變量內容從序列化的對象從新讀到內存裏稱之爲反序列化,即unpickling。

JSON和Python內置的數據類型對應以下:

複製代碼
1 import json
 2
 3 dic={'name':'alvin','age':23,'sex':'male'}
 4 print(type(dic))#<class 'dict'>
 5
 6 j=json.dumps(dic)
 7 print(type(j))#<class 'str'>
 8
 9
10 f=open('序列化對象','w')
11 f.write(j)  #-------------------等價於json.dump(dic,f)
12 f.close()
13 #-----------------------------反序列化<br>
14 import json
15 f=open('序列化對象')
16 data=json.loads(f.read())#  等價於data=json.load(f)



import json
#dct="{'1':111}"#json 不認單引號
#dct=str({"1":111})#報錯,由於生成的數據仍是單引號:{'one': 1}

dct='{"1":"111"}'
print(json.loads(dct))

#conclusion:
#        不管數據是怎樣建立的,只要知足json格式,就能夠json.loads出來,不必定非要dumps的數據才能loads
複製代碼

實例

複製代碼
import json

# 序列化
info = {'name':'derek','age':'22'}

with open('test','w') as f:
    f.write(json.dumps(info))

# 反序列化
with open('test','r') as f:
    info = json.loads(f.read())
    print(info)
複製代碼

pickle  (它只能用於Python)

複製代碼
1 import pickle
 2
 3 dic={'name':'alvin','age':23,'sex':'male'}
 4
 5 print(type(dic))#<class 'dict'>
 6
 7 j=pickle.dumps(dic)
 8 print(type(j))#<class 'bytes'>
 9
10
11 f=open('序列化對象_pickle','wb')#注意是w是寫入str,wb是寫入bytes,j是'bytes'
12 f.write(j)  #-------------------等價於pickle.dump(dic,f)
13
14 f.close()
15 #-------------------------反序列化
16 import pickle
17 f=open('序列化對象_pickle','rb')
18
19 data=pickle.loads(f.read())#  等價於data=pickle.load(f)
20
21
22 print(data['age'])   
複製代碼

總結:

Json模塊提供了四個功能:dumps、dump、loads、load

pickle模塊提供了四個功能:dumps、dump、loads、load

  dump()函數接受一個文件句柄和一個數據對象做爲參數,把數據對象以特定的格式保存 到給定的文件中。當咱們使用load()函數從文件中取出已保存的對象時,pickle知道如何恢復這些對象到它們原本的格式。

  dumps()函數執行和dump() 函數相同的序列化。取代接受流對象並將序列化後的數據保存到磁盤文件,這個函數簡單的返回序列化的數據。

  loads()函數執行和load() 函數同樣的反序列化。取代接受一個流對象並去文件讀取序列化後的數據,它接受包含序列化後的數據的str對象, 直接返回的對象。

configparser模塊

用於生成和修改常見配置文檔

 配置文件

複製代碼
[default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9

[bitbucket.org]
user = hg

[topsecret.server.com]
port = 50022
forwardx11 = no
複製代碼

用python生成這樣的一個配置文檔

複製代碼
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'] = {'port':'50022', 'Forwardx11':'no'}
with open(
'example.ini','w') as configfile: config.write(configfile)
複製代碼

讀取

複製代碼
import configparser
config
= configparser.ConfigParser() print(config.read('example.ini'))
#查看全部的標題 print(config.sections()) #['default', 'bitbucket.org', 'topsecret.server.com']
#查看標題section1下全部key=value的key
options = config.options('default') print(options) #['serveraliveinterval', 'compression', 'compressionlevel']

#查看標題section1下全部key=value的(key,value)格式 items_list = config.items('topsecret.server.com') print(items_list) #[('port', '50022'), ('forwardx11', 'no')]
複製代碼

增刪改查

複製代碼
import configparser

config = configparser.ConfigParser()
config.read('example.ini',encoding = 'utf-8')

#刪除整個標題
config.remove_section('bitbucket.org')

#刪除標題下的option
config.remove_option('topsecret.server.com','port')

#添加一個標題
config.add_section('info')
#在標題下添加options
config.set('info','name','derek')

#判斷是否存在
print(config.has_section('info'))        #True
print(config.has_option('info','name'))    #True

#將修改的內容存入文件
config.write(open('new_example.ini','w'))
複製代碼
複製代碼
#修改後的文件

[default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9

[topsecret.server.com]
forwardx11 = no

[info]
name = derek
複製代碼

hashlib模塊

複製代碼
hash:一種算法 ,3.x裏代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
三個特色:
1.內容相同則hash運算結果相同,內容稍微改變則hash值則變
2.不可逆推
3.相同算法:不管校驗多長的數據,獲得的哈希值長度固定。
複製代碼
複製代碼
 1 import hashlib
 2
 3 m=hashlib.md5()# m=hashlib.sha256()
 4
 5 m.update('hello'.encode('utf8'))
 6 print(m.hexdigest())  #5d41402abc4b2a76b9719d911017c592
 7
 8 m.update('alvin'.encode('utf8'))
 9
10 print(m.hexdigest())  #92a7e713c30abbb0319fa07da2a5c4af
11
12 m2=hashlib.md5()
13 m2.update('helloalvin'.encode('utf8'))
14 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
15
16 '''
17 注意:把一段很長的數據update屢次,與一次update這段長數據,獲得的結果同樣
18 可是update屢次爲校驗大文件提供了可能。
複製代碼

re模塊

複製代碼
# 正則匹配
import re

# \w與\W 字母數字下劃線
print(re.findall('\w', 'hello derek \n 123'))
print(re.findall('\W', 'hello derek \n 123'))
# ['h', 'e', 'l', 'l', 'o', 'd', 'e', 'r', 'e', 'k', '1', '2', '3']
# [' ', ' ', '\n', ' ']

# \s與\S  匹配任意空白字符
print(re.findall('\s', 'hello  egon  123'))  # [' ', ' ', ' ', ' ']
print(re.findall('\S', 'hello  egon  123'))  # ['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

# \n \t都是空,均可以被\s匹配
print(re.findall('\s', 'hello \n egon \t 123'))  # [' ', '\n', ' ', ' ', '\t', ' ']

# \n與\t
print(re.findall(r'\n', 'hello egon \n123'))  # ['\n']
print(re.findall(r'\t', 'hello egon\t123'))  # ['\n']

# \d與\D
print(re.findall('\d', 'hello egon 123'))  # ['1', '2', '3']
print(re.findall('\D', 'hello egon 123'))  # ['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']

# \A與\Z   \A  匹配字符串開始  \Z 匹配字符串結束
print(re.findall('\Ahe', 'hello egon 123'))  # ['he'],\A==>^
print(re.findall('123\Z', 'hello egon 123'))  # ['he'],\Z==>$

# ^與$
print(re.findall('^h', 'hello egon 123'))  # ['h']
print(re.findall('3$', 'hello egon 123'))  # ['3']

# 重複匹配:| . | * | ? | .* | .*? | + | {n,m} |
# .  匹配任意字符,除了換行符,除非re.DOTALL標記
print(re.findall('a.b', 'a1b'))  # ['a1b']
# a和b中間匹配任意一個字符
print(re.findall('a.b', 'a1b a*b a b aaab'))  # ['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b', 'a\nb'))  # []
print(re.findall('a.b', 'a\nb', re.S))  # ['a\nb']
print(re.findall('a.b', 'a\nb', re.DOTALL))  # ['a\nb']同上一條意思同樣
print(re.findall('a...b', 'a123b'))  # ['a123b']

# *匹配*號前的字符0次或屢次
print(re.findall('ab*', 'bbbbbbb'))  # []
print(re.findall('ab*', 'a'))  # ['a']
print(re.findall('ab*', 'abbbb'))  # ['abbbb']
print(re.findall('ab*', 'abababbabbbb'))  # ['ab', 'ab', 'abb', 'abbbb']

# ?   匹配前一個字符1次或0次
print(re.findall('ab?', 'a'))  # ['a']
print(re.findall('ab?', 'abbb'))  # ['ab']
# 匹配全部包含小數在內的數字
print(re.findall('\d+\.?\d*', "asdfasdf123as1.13dfa12adsf1asdf3"))  # ['123', '1.13', '12', '1', '3']

# .*默認爲貪婪匹配
print(re.findall('a.*b', 'a1b22222222b'))  # ['a1b22222222b']

# .*?爲非貪婪匹配:推薦使用
print(re.findall('a.*?b', 'a1b22222222b'))  # ['a1b']

# +   匹配前一個字符1次或屢次
print(re.findall('ab+', 'abbaabb'))  # ['abb', 'abb']
print(re.findall('ab+', 'abbb'))  # ['abbb']

# {n,m}  匹配前一個字符n到m次
print(re.findall('ab{2}', 'abbb'))  # ['abb']
print(re.findall('ab{2,4}', 'abbb'))  # ['abb']
print(re.findall('ab{1,}', 'abbb'))  # 'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}', 'abbb'))  # 'ab{0,}' ===> 'ab*'

# []
print(re.findall('a[1*-]b', 'a1b a*b a-b'))  # []內的都爲普通字符了,且若是-沒有被轉意的話,應該放到[]的開頭或結尾
print(re.findall('a[^1*-]b', 'a1b a*b a-b a=b'))  # []內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[0-9]b', 'a1b a*b a-b a=b'))  # []內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[a-z]b', 'a1b a*b a-b a=b aeb'))  # []內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[a-zA-Z]b', 'a1b a*b a-b a=b aeb aEb'))  # []內的^表明的意思是取反,因此結果爲['a=b']

# \# print(re.findall('a\\c','a\c')) #對於正則來講a\\c確實能夠匹配到a\c,可是在python解釋器讀取a\\c時,會發生轉義,而後交給re去執行,因此拋出異常
print(re.findall(r'a\\c', 'a\c'))  # r表明告訴解釋器使用rawstring,即原生字符串,把咱們正則內的全部符號都當普通字符處理,不要轉義
print(re.findall('a\\\\c', 'a\c'))  # 同上面的意思同樣,和上面的結果同樣都是['a\\c']

# (): 匹配括號裏面的內容
print(re.findall('ab+', 'ababab123'))  # ['ab', 'ab', 'ab']
print(re.findall('(ab)+123', 'ababab123'))  # ['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123', 'ababab123'))  # findall的結果不是匹配的所有內容,而是組內的內容,?:可讓結果爲匹配的所有內容

# |
print(re.findall('compan(?:y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))
複製代碼

一些方法

# ===========================re模塊提供的方法介紹===========================
import re
#1
print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回全部知足匹配條件的結果,放在列表裏
#2
print(re.search('e','alex make love').group()) #e,只到找到第一個匹配而後返回一個包含匹配信息的對象,該對象能夠經過調用group()方法獲得匹配的字符串,若是字符串沒有匹配,則返回None。

#3
print(re.match('e','alex make love'))    #None,同search,不過在字符串開始處進行匹配,徹底能夠用search+^代替match

#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割獲得''和'bcd',再對''和'bcd'分別按'b'分割

#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默認替換全部
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex

print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),結果帶有總共替換的個數


#6
obj=re.compile('\d{2}')

print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj
View Code

shelve模塊

shelve模塊比pickle模塊簡單,只有一個open函數,返回相似字典的對象,可讀可寫;key必須爲字符串,而值能夠是python所支持的數據類型

import shelve

f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}

print(f['stu1_info']['hobby'])
f.close()
View Code

 logging模塊

 不少程序都有記錄日誌的需求,而且日誌中包含的信息即有正常的程序訪問日誌,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日誌接口,你能夠經過它存儲各類格式的日誌,logging的日誌能夠分爲 debug、info、warning、error、critical5個級別

1.模塊初始

複製代碼
import logging

logging.warning('wrong password more than 3 times')
logging.critical('server is down')
logging.error('error message')


結果:
WARNING:root:wrong password more than 3 times
CRITICAL:root:server is down
ERROR:root:error message
複製代碼

2.logging模塊五個級別

相關文章
相關標籤/搜索