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'

參考資料

  1. http://www.cnblogs.com/tkqasn/p/6005025.html
  2. http://www.cnblogs.com/wupeiqi/articles/4963027.html
  3. http://www.cnblogs.com/alex3714/articles/5161349.html
  4. http://egon09.blog.51cto.com/9161406/1840425
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章