python 之經常使用模塊

模塊(module):python

模塊實質是一個python文件,也就是把python代碼寫到模塊裏面。mysql

模塊分類:linux

標準庫:python內置git

開源模塊:第三方正則表達式

自定義模塊:本身寫算法

 

1、os , sys 模塊sql

import os, sys

print(os.getcwd())     #獲取當前目錄

os.chmod("/usr/share", 7)   #給/usr/share目錄添加權限

print(os.curdir)  #當前目錄

print(os.pardir)  #父目錄

print(os.makedirs("/usr/local/mysql"))   #遞歸建立目錄,父目錄不存在時建立目錄

print(os.removedirs("/usr/local/mysql"))  #遞歸刪除空目錄

print(os.mkdir("new"))  #建立文件夾

os.rename("old", "new")  #重命名

print(os.path.join("/root",'mysql','rack.sql')) #拼接成一個路徑

print(os.path.split("/usr/mysql/123.txt"))     #分割路徑和文件名

print(os.sep)        #當前操做系統的路徑分隔符

print(os.linesep)    #當前操做系統的換行符

print(os.pathsep)  #當前系統的環境變量中每一個路徑的分隔符,linux是:,windows是;
  
print(os.environ)  #當前系統的環境變量

print(os.path.abspath(__file__))   #獲取絕對路徑

print(sys.version)    #獲取系統版本

print(sys.argv)        #命令行參數List,第一個元素是程序自己路徑

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

print(sys.platform)  #返回操做系統名稱

sys.stdout.write('please:')   #向屏幕輸出一句話

print(sys.maxsize)   #最大值

2、random, string模塊windows

import random, string

print(random.random())  #隨機取浮點數,默認是0~1,不能指定取值範圍

print(random.randint(1,18))  #隨機取整數

print(random.randrange(1,28))   #隨機產生一個range

print(random.choice('sjdkf93f')   #隨機選擇一個元素

print(random.sample('hello', 3))  #隨機取3個元素

print(random.uniform(1, 9))     #隨機取浮點數,能夠指定取值範圍

f = [1, 2, 3, 4, 5]

random.shuffle(f)   #打亂順序

print(f)

print(string.ascii_letters+string.digits)       #全部的數字和字母

3、time&timedate模塊dom

時間有三種表示方式,一種是時間戳、一種是格式化時間、一種是時間元組函數

import time, timedate

print(time.timezone())    #和標準時間相差的時間,單位是s

print(time.time())    #獲取當前的時間戳

print(time.sleep(1))   #休息1s

print(time.gmtime())#把時間戳轉換成時間元組,若是不傳的話,默認取標準時區的時間戳

print(time.localtime())#把時間戳轉換成時間元組,若是不傳的話,默認取當前時區的時間戳

print(time.mktime(time.localtime())) #把時間元組轉換成時間戳 print(time.strftime("%y%n%d %H%M%S")) #將時間元組轉換成格式化輸出的字符串 print(time.strptime("20170908 182719","%Y%m%d %H%M%S"))#將格式化的時間轉換成時間元組 print(datetime.datetime.now()) #當前時間格式化輸出 print(datetime.datetime.now()+datetime.timedelta(3)) #3天后的時間 print(datetime.datetime.now()+datetime.timedelta(-3)) #3天前的時間

 5、shelve模塊

shelve模塊用來持久化存儲數據,shelve模塊能夠存儲list、字典、函數、類等,shelve模塊是key-value存儲的,value是存儲內容。

import shelve

s = shelve.open('shelve_test', 'r')   

class Test(object):

    def __init__(self, n):

        self.n = n

t = Test(1234)
t1 = Test('abcd')

def func():

     print('hello world')

name = ['tom', 'jane', 'rose']

d['test'] = name
d['t'] = t
d['t1'] = t1
d['t2'] = func

print(d.get('t2'))
d.close()

 6、hashlib模塊

hashlib模塊,主要用於加密相關操做,主要提供sha一、sha25六、sha38四、sha5十二、MD5算法

import hashlib

m = hashlib.md5()
m.update(b"hello, linda")
m.update(b"it's me")
print(m.digest())
m.update(b"It has been a long time since we ... ")

print(m.digest())   #2進制hash
print(len(m.hexdigest()))  #16進制hash

hash = hashlib.md5()
hash.update(b'admin')
print(hash.hexdigest())

hash = hashlib.sha1()
hash.update(b'admin')
print(hash.hexdigest())

hash = hashlib.sha256()
hash.update(b'admin')
print(hash.hexdigest())

hash = hashlib.sha384()
hash.update(b'admin')
print(hash.hexdigest())

hash = hashlib.sha512()
hash.update(b'admin')
print(hash.hexdigest())

7、configparser模塊

configparser模塊用來操做配置文件,用於生成和修改配置文件,python2中爲ConfigParser。

常見的配置文件以下:

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

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

使用configparser模塊能夠生成一個這樣的文檔:

import configparser

class myconf(configparser.ConfigParser):
    def __init__(self):
        configparser.ConfigParser.__init__(self, defaults=None)
    def optionxform(self, optionstr):
        return optionstr
    
config = myconf()
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['Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
with open('my.conf', 'w') as configfile:
    config.write(configfile)

 如下是一些經常使用的操做,修改、添加、刪除節點和屬性

import configparser

class myconf(configparser.ConfigParser):
    def __init__(self):
        configparser.ConfigParser.__init__(self, defaults=None)
    def optionxform(self, optionstr):
        return optionstr

config = myconf()

config.read('my.conf')

sections = config.sections()  # 獲取全部節點

print(sections)

items = config.items('DEFAULT')  # 獲取指定節點下的全部鍵值對

print(items)

options = config.options('bitbucket.org')  # 獲取指定節點下的全部鍵(DEFAULT默認節點下的鍵也會展現)

print(options)

print(config.get('bitbucket.org', 'User'))  # 獲取對應節點下的key值

config.add_section('NEW')  # 增長節點

config.set('NEW', 'test', 'true')  # 增長節點下面對應的屬性和值

config.set('DEFAULT', 'hk', '2333')  # 修改節點下的屬性

with open("my.conf", "w") as d:  # 寫入修改後的文件
    config.write(d)

print(config.has_option('NEW', 'test'))  # 節點下是否有對應的屬性

print(config.has_section('NEW'))  # 是否有該節點

config.remove_section('NEW')  # 刪除節點

config.write(open("my.conf", "w"))  # 把刪除寫入文件

d.close()

運行結果:

['bitbucket.org', 'topsecret.server.com']
[('ServerAliveInterval', '45'), ('Compression', 'yes'), ('CompressionLevel', '9'), ('ForwardX11', 'yes')]
['User', 'ServerAliveInterval', 'Compression', 'CompressionLevel', 'ForwardX11']
hg
True
True

8、re模塊

re模塊是正則表達式模塊,用來匹配一些特定的字符串。

如下是一些經常使用的正則表達式符號

'.'        默認匹配除\n以外的任意一個字符,若指定 flag DOTALL,則能夠匹配任意字符。
'^'        匹配字符開頭,若指定flag MULTILINE,這種能夠匹配上(r"^a", "\nabc\neee", flag=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() 結果 abccbaca456c
'\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

經常使用的匹配語法:

re.match     #從頭開始匹配
re.search    #匹配包含
re.findall   #把全部匹配到的字符放到列表以元素的形式展現
re.splitall  #以匹配到的字符當作列表分隔符
re.sub       #匹配字符並替換

 9、xlrd、xlwt、xlutils模塊

Python操做Excel文件須要xlrd、xlwt、xlutils等模塊,xlrd用來讀取Excel,xlwt用來寫Excel,xlutils用來修改Excel,可使用pip安裝,也能夠在pycharm的setting裏安裝。

一、xlrd模塊,具體用法以下:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import xlrd

open_wb = xlrd.open_workbook('demo.xls')    # 打開Excel文件,該文件不存在會報錯

print(open_wb.sheet_names())    # 獲取全部sheet頁的名字

sheet_name = open_wb.sheet_by_name('sheet1')  # 按照名字查找第二張表單

sheet_index = open_wb.sheet_by_index(0)    # 根據sheet頁的索引獲取sheet內容

print(sheet_name.nrows)    # 獲取sheet_name的行數
print(sheet_name.ncols)    # 獲取sheet_name的列數

for row_num in range(sheet_name.nrows):    # 循環獲取每行的數據
    print(sheet_name.row_values(row_num))    # 獲取每行數據

cell_A2 = sheet_index.cell(1, 1).value    # 獲取指定單元格的值,第一個值是行,第二個值是列

print(cell_A2) 

二、xlwt模塊,用來寫入Excel

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import xlwt
title = ['姓名', '年齡', '性別', '段位']
status = [['德瑪', '27', '', '青銅'], ['艾希', '26', '', '黃金'], ['亞瑟', '28', '', '白銀']]

new_wb = xlwt.Workbook()     # 新建一個Excel對象

sheet = new_wb.add_sheet('Legends')     # 添加一個名爲Legends的sheet頁

for i in range(len(title)):
    sheet.write(0, i, title[i])     # 寫入表頭

for i in range(len(status)):
    for j in range(4):
        sheet.write(i+1, j, status[i][j])     # 循環寫入每行數據
new_wb.save('legend.xls')     # 保存數據到legend.xls中,不支持後綴爲.xlsx的格式

三、xlutils模塊,修改Excel的內容,不能直接修改原來的Excel內容,須要先複製一個心得Excel文件,用法以下:

 1 #!/usr/bin/env python
 2 # _*_ coding:utf-8 _*_
 3 
 4 from xlrd import open_workbook     # 導入xlrd中的打開Excel模塊
 5 from xlutils.copy import copy           # 導入xlutils.copy中的複製Excel模塊
 6 open_wb = open_workbook('legend.xls')
 7 
 8 index_wb = open_wb.sheet_by_index(0)   # 經過索引獲取sheet
 9 
10 copy_wb = copy(open_wb)     # 複製一個Excel
11 
12 sheet_wb = copy_wb.get_sheet(0)    # 獲取到新的Excel裏面的sheet
13 
14 sheet_wb.write(1, 0, '蒙多')    # 修改原文件的第1行第0列爲'蒙多'
15 
16 copy_wb.save('legend_new.xls')     # 保存新的Excel,後綴名爲xls,不支持後綴名爲xlsx
相關文章
相關標籤/搜索