1. 程式人生 > >python基礎之五——模組

python基礎之五——模組

本部落格所有文章僅僅是博主做筆記之用,部落格內容並不詳細(以後有空會修改完善),思維也有跳躍之處,想詳細學習部落格內容可參考文章後面的參考連結,祝學習快樂。

本節要點:
1. 定義
2. 匯入方法
3. import的本質
4. 匯入優化
5. 模組的分類

1.定義

模組:用來從邏輯上組織python程式碼,本質是一個.py檔案

2.匯入方法

3.import本質

匯入模組的本質就是把.py檔案解釋一遍
匯入包的本質就是執行該包下的_init_.py檔案

4.匯入優化

import moudle_test
moudle_test.test() #執行1000遍的話需要在moudle_test資料夾下尋找1000遍,耗時間

優化:

from moudle_test import test
test() # 這樣不需要每次去找

5.分類

  • 內建模組(標準庫)
  • 開源模組
  • 自定義模組

time和datetime

1)時間戳,從1970.01.01到現在的秒數

>>> import time
>>> time.time()
1496627063.7224042   #哈哈,以後玩解密遊戲可以考慮加入此元素

2)格式化字串

>>> time.strftime("%Y-%m-%d  %H:%M:%S",time
.localtime()) '2017-06-04 20:28:13' >>> time.strptime('2017-06-04 20:28:13',"%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2017, tm_mon=6, tm_mday=4, tm_hour=20, tm_min=28, tm_sec=13, tm_wday=6, tm_yday=155, tm_isdst=-1)

3)元組(struct_time)

>>> time.gmtime()
time.struct_time(tm_year=2017
, tm_mon=6, tm_mday=4, tm_hour=12, tm_min=8, tm_sec=9, tm_wday=6, tm_yday=155, tm_isdst=0) >>> time.localtime() time.struct_time(tm_year=2017, tm_mon=6, tm_mday=4, tm_hour=20, tm_min=8, tm_sec=18, tm_wday=6, tm_yday=155, tm_isdst=0) >>> time.gmtime(0) time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) >>> time.gmtime(1234213425) #將時間戳轉化為元組格式 time.struct_time(tm_year=2009, tm_mon=2, tm_mday=9, tm_hour=21, tm_min=3, tm_sec=45, tm_wday=0, tm_yday=40, tm_isdst=0) >>> a=time.localtime() >>> time.mktime(a) #將元組格式轉化為時間戳 1496578908.0

time.gmtime():結果為UTC時間
time.localtime():結果為UTC+8時區
這裡寫圖片描述

這裡寫圖片描述

random

>>> import random
>>> random.random()   #[0,1) 取不到1
0.6227119560477493  
>>> random.randint(3,8)   #[a,b] 兩頭都能取到
3
>>> random.randrange(2,5,2) #randrange(start, stop=None, step=1) 可以取到start,取不到stop
2
>>> random.choice([1,2,3,4])  #random.choice(seq) 非空序列隨機選擇一個元素
3
>>> random.sample({1,2,3,4,4,5,6,7,8,2},2)
[5, 1]     # random.sample(population, k)  總體序列或者集合中隨機選擇k個不重複的元素
>>> random.uniform(1,2) #指定區間[a,b)中取一個浮點數
1.3309574832594642

>>> x=list(range(10))
>>> random.shuffle(x)   #打亂順序,注意這個函式的返回值為None,傳入的值變了,需要儲存原值的話注意備份
>>> x
[5, 1, 7, 3, 2, 0, 4, 9, 6, 8]


>>> x
[5, 1, 7, 3, 2, 0, 4, 9, 6, 8]
>>> p=random.shuffle(x)
>>> p
>>> x
[0, 5, 7, 9, 1, 3, 6, 8, 4, 2]
>>> type(x)
<class 'list'>
>>> 
>>> type(p)
<class 'NoneType'>

os模組

os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑
os.chdir("dirname")  改變當前指令碼工作目錄;相當於shell下cd
os.curdir  返回當前目錄: ('.')
os.pardir  獲取當前目錄的父目錄字串名:('..')
os.makedirs('dirname1/dirname2')    可生成多層遞迴目錄
os.removedirs('dirname1')    若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir('dirname')    生成單級目錄;相當於shell中mkdir dirname
os.rmdir('dirname')    刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir('dirname')    列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印
os.remove()  刪除一個檔案
os.rename("oldname","newname")  重新命名檔案/目錄
os.stat('path/filename')  獲取檔案/目錄資訊
os.sep    輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/"
os.linesep    輸出當前平臺使用的行終止符,win下為"\t\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模組後寫了個簡單的批量重新命名指令碼檔案。以下是程式碼:

import os
def renames(path,new_names):
    """
    批量重新命名指令碼,path為需要重新命名的檔案路徑,格式為r"C:\python\test"或者"C:\\python\\test"都行。new_names為新名字組成的一個列表或元組
    """
    old_names=os.listdir(path) #獲得的檔名會按名稱排序,要注意10.txt會在2.txt檔案之前
    n=len(old_names)
    for i in range(n):
        print(old_names[i],"------->",new_names[i]+"."+old_names[i].split('.')[-1])

    choice=input("重新命名結果如上,你確定嗎?(確定:y;退出:n)")

    if choice.strip()=='y':
        for i in range(n):
            os.rename(path+"\\"+old_names[i],path+'\\'+new_names[i]+"."+old_names[i].split('.')[-1])
        print("已完成。")
    else:
        exit("已退出。")

sys模組

方法

    displayhook() -- print an object to the screen, and save it in builtins._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setcheckinterval() -- control how often the interpreter checks for events
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

Static objects:

    builtin_module_names -- tuple of module names built into this interpreter
    copyright -- copyright notice pertaining to this interpreter
    exec_prefix -- prefix used to find the machine-specific Python library
    executable -- absolute path of the executable binary of the Python interpreter
    float_info -- a struct sequence with information about the float implementation.
    float_repr_style -- string indicating the style of repr() output for floats
    hash_info -- a struct sequence with information about the hash algorithm.
    hexversion -- version information encoded as a single integer
    implementation -- Python implementation information.
    int_info -- a struct sequence with information about the int implementation.
    maxsize -- the largest supported length of containers.
    maxunicode -- the value of the largest Unicode code point
    platform -- platform identifier
    prefix -- prefix used to find the Python library
    thread_info -- a struct sequence with information about the thread implementation.
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    dllhandle -- [Windows only] integer handle of the Python DLL
    winver -- [Windows only] version number of the Python DLL

json和pickle模組

用於序列化的兩個模組

  • json,用於字串 和 python資料型別間進行轉換
  • pickle,用於python特有的型別 和 python的資料型別間進行轉換

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

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

json

encoding:

dumps:  將物件序列化

#coding:utf-8
import json

# 簡單編碼===========================================
>>> print(json.dumps(['foo',{'bar':('baz', None, 1.0, 2)}]))
#["foo", {"bar": ["baz", null, 1.0, 2]}]

#字典排序
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
#{"a": 0, "b": 0, "c": 0}

#自定義分隔符
print(json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':')))
# [1,2,3,{"4":5,"6":7}]
print(json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=('/','-')))
# [1/2/3/{"4"-5/"6"-7}]

#增加縮排,增強可讀性,但縮排空格會使資料變大
print(json.dumps({'4': 5, '6': 7}, sort_keys=True,indent=2, separators=(',', ': ')))
# {
#   "4": 5,
#   "6": 7
# }

# 另一個比較有用的dumps引數是skipkeys,預設為False。
# dumps方法儲存dict物件時,key必須是str型別,如果出現了其他型別的話,那麼會產生TypeError異常,如果開啟該引數,設為True的話,會忽略這個key。
data = {'a':1,(1,2):123}
print(json.dumps(data,skipkeys=True))
#{"a": 1}

dump: 將物件序列化並儲存到檔案

import json
obj = ['foo', {'bar': ('baz', None, 1.0, 2)}]
with open("json.txt","w") as f:
    json.dump(obj,f)

loads:  將序列化字串反序列化

with open("json.txt") as f:
    data=f.read()
    print(json.loads(data))

load:  將序列化字串從檔案讀取並反序列化

with open("json.txt") as f:
    print(json.load(f))

json只支援簡單的資料型別,例如我們碰到物件datetime,或者自定義的類物件等json預設不支援的資料型別時,就會出錯。

import json,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","w") as f:
    json.dump(dt,f)

TypeError: Object of type ‘datetime’ is not JSON serializable

pickle

python的pickle模組實現了python的所有資料序列和反序列化。基本上功能使用和JSON模組沒有太大區別,方法也同樣是dumps/dump和loads/load。

與JSON不同的是pickle不是用於多種語言間的資料傳輸,它僅作為python物件的持久化或者python程式間進行互相傳輸物件的方法,因此它支援了python所有的資料型別。

dumps

import pickle,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","wb") as f:
    info=pickle.dumps(dt)  #二進位制格式檔案
    f.write(info)

這不是亂碼,pickle存進去的效果就是這樣的

dump

import pickle,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","wb") as f:
    pickle.dump(dt,f)

loads

import pickle,datetime

with open("json.txt","rb") as f:
    print(pickle.loads(f.read()))

load

import pickle,datetime

with open("json.txt","rb") as f:
    print(pickle.load(f))

shelve模組

shelve模組是一個簡單的k,v將記憶體資料通過檔案持久化的模組,可以持久化任何pickle可支援的python資料格式。

import shelve
import datetime
d = shelve.open('shelve_test')  # 開啟一個檔案

info =  {'age':22,"job":'it'}
name = ["alex", "rain", "test"]
time_now = datetime.datetime.now()

d["name"] = name  # 持久化列表
d["info"] = info  # 持久dict
d['date'] = time_now
d.close()
import shelve
import datetime
d = shelve.open('shelve_test')  # 開啟一個檔案
print(d.get("name"))
print(d.get("info"))
print(d.get("date"))
d.close()

xml模組

xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單。

xml的格式如下,就是通過<>節點來區別資料結構的:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml:

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)

#遍歷xml文件
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)

#只遍歷year 節點
for node in root.iter('year'):
    print(node.tag,node.text)

修改和刪除xml文件內容

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) + 1
    node.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')

自己建立xml文件

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) #生成文件物件
et.write("test.xml", encoding="utf-8",xml_declaration=True)

ET.dump(new_xml) #列印生成的格式

ConfigParser模組

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

常見格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[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'] = {}
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)

讀:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
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'

configparser增刪改查語法:

[section1]
k1 = v1
k2:v2

[section2]
k1 = v1

import ConfigParser

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

hashlib模組

用於加密相關的操作,3.x裡代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法

>>> import hashlib
>>> m=hashlib.md5() #一個空的物件,md5換成其他的用法一樣
>>> m
<md5 HASH object @ 0x00000234E588C3F0>
>>> m.hexdigest() #顯示出來
'd41d8cd98f00b204e9800998ecf8427e'  
>>> hashlib.md5(b"").hexdigest() 
'd41d8cd98f00b204e9800998ecf8427e'  
>>> m.update(b"yang")
>>> m.hexdigest()
'57cb5a26334a6c1d5e27c49def4a0f0d'
>>> m.update(b"hello")  #和上面的值合在一起再求MD5值
>>> m.hexdigest()
'00d2da9375872dc0bd23c1030bd6a2e4'
>>> hashlib.md5(b"yanghello").hexdigest()
'00d2da9375872dc0bd23c1030bd6a2e4'
>>> hashlib.md5("python中文".encode()).hexdigest()
'e9ee79e44a5430955c4baced327b57c4'

re模組

  • match (從頭開始匹配)
  • search
  • findall
  • split
  • sub
  • -
'.'     預設匹配除\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'

參考資料