python 四 經常使用模塊

什麼是模塊:
  
模塊實質上就是一個python文件,它是用來組織代碼的,意思就是說把python代碼寫到裏面,文件名就是模塊的名稱,test.py:test就是模塊名稱python

安裝模塊:連網時直接用pip方法一,沒連網須要下載對應模塊包進行安裝方法二,三。mysql

方法一:cmd下使用  pip install xlwt   (xlwt 這個是模塊名稱)  git

或者python -m pip install --upgrade pip -i https://pypi.douban.com/simplesql

方法二:模塊以.whl結尾的直接在 pip install c:/user/niuhanyang/desktop/xxx.whl#後面跟對應文件路徑數據庫

方法三:模塊以.tar.gz結尾的     (1.先解壓,2.解壓以後在命令行裏面進入到這個目錄下,3.執行python setup.py installjson

模塊的更新:  pip install -U 模塊名稱api

pip升級時界面有時會出現鏈接超時能夠用如下方法:使用timeout參數增長時間  cookie

python -m pip install --upgrade pip  --timeout 6000app

標準模塊:python自帶的模塊,不須要再下載的模塊例如:os,time,random,hashlib 等等dom

模塊導入查詢:import導入文件時先從當前目錄下尋找,在從環境變量文件下面進行查找。

查找當前安裝模塊並導出來:   pip freeze > e:\pip_list.txt

安裝文件內的模塊:  pip install -r e:\pip_list.txt

使用pycharm開發時須要引用其餘文件內的模塊有兩種方法:

1.直接選擇對應模塊右鍵mark directory as--sources root(sources root 主要是把當前的目錄變成跟目錄便於配置內的數據操做)

2.使用path路徑方法進行添加

1.excel模塊

寫excel

import xlwt  #寫excel 只寫不讀
book = xlwt.Workbook()
sheet = book.add_sheet('chahca')#任意寫一個參數
#sheet.write(0,0,'id')#  單個寫 行,列,內容
stus = [
    [1,'njf','1234','xiaoxiao','wangming'],
    [2,'xiaojun','1234','xiaoxiao'],
    [3,'hailong','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
    [4,'xiaohei','1234','xiaoxiao'],
]
line = 0  # 控制行數
for stu in stus:
    col = 0   # 定義 列
    for s in stu:
        sheet.write(line,col,s) #指定行,列以及內容
        col += 1  #循環一次加一次列
    line += 1   #沒循環一次加一次
book.save('sht.xls')#保存到文件內
View Code

讀取excel

import xlrd
#xlrd:讀取execl,
wenben =xlrd.open_workbook("jinniug.xls")#這個文件名稱必須的在這個目錄下
#沒有就要寫這個文件的絕對路徑
wenjian = xlrd.open_workbook("C:\\Users\Administrator\Desktop\FTP帳號.xlsx")
sheet = wenjian.sheet_by_index(0)#獲取當前文件多少頁
print(sheet.nrows) #excel裏面有多少行
print(sheet.ncols) #excel裏面有多少列
day = sheet.cell(1,1).value#獲取那一列,那一行的數據,若是沒有對應的會報錯
print(day)
for i in range(sheet.nrows):#循環獲取每行的內容
    print(sheet.row_values(i)[1:2])  #'[1:2]' 獲取這一行內那一列到那一列的數據
print(sheet.row_values(1))#獲取到整行的內容
讀取excel表格

 修改excel

import xlrd
import xlutils #修改excel表格
from xlutils import copy
book = xlrd.open_workbook('stu.xls')
#先用xlrd打開一個Excel
new_book = copy.copy(book)
#而後用xlutils裏面的copy功能,複製一個Excel
sheet = new_book.get_sheet(0)#獲取sheet頁
sheet.write(0,1,'xiaomming')
sheet.write(1,1,'xiaojun')
View Code

練習題:獲取表格內某幾列數據

import xlrd
def get_case(path):
    all_case = []
    book = xlrd.open_workbook(path)
    sheet = book.sheet_by_index(0)
    for i in  range(1,sheet.nrows):
        row_data = sheet.row_values(i)[4:8]
        all_case.append(row_data)
    return all_case
res =get_case('xxxxxxx.xls')
print(res)
View Code

2.加密模塊  hashlib

import hashlib
password = '123456789'
m = hashlib.md5(password.encode())#字符串不能直接加密,須要轉成二級制後才能加密
print(m.hexdigest())#返回密文


#加鹽就是隨機在原有的密碼上在加上一串字符
#加鹽操做
def my_md5(s:str,salt=None):
    #salt是鹽值
    s = str(s)
    if salt:
        s = s+salt
    m = hashlib.md5(s.encode()) #轉換爲二進制在加鹽
    return m.hexdigest()
View Code

3.拼音模塊 

import xpinyin
s = xpinyin.Pinyin()
p = xpinyin.Pinyin()   #實例化
res = p.get_pinyin('烘乾') #默認不傳後面的話,兩個拼音之間會有- 連接
print(res)
print(s.get_pinyin('王明',''))#若是須要去掉空格後面以空來鏈接
View Code

4.操做數據庫

數據庫創建或查詢(1.連接數據庫:帳號、密碼、ip、端口號、數據庫;2.創建遊標;3.執行sql(執行insert、delete、update語句時,必須得commit)4.獲取結果;5.關閉遊標;6.鏈接關閉;)

import pymysql
host='1.1.1.'#數據庫地址例如:192.168.1.1
user='jxz' #帳號
password='123456' #密碼只能是字符串
db='jxz'  #數據庫
port=3306#端口號只能寫int類型
charset='utf8'#只能寫utf8,不能寫utf-8
import pymysql
conn = pymysql.connect(host=host,password=password,
                user=user,db=db,port=port,
                charset=charset,autocommit=True
                )#創建鏈接數據庫方法 connect,加了autcommit=True後就不須要commit了
cur = conn.cursor()#創建遊標,(須要數據庫管理員進行那東西或放東西)
cur.execute('select * from app_myuser limit 5;')#只幫你執行sql語句
cur.commit()#執行sql語句時除了查詢不commit,其餘都須要,否則不能提交
#print(cur.fetchall())#獲取數據庫全部結果
print(cur.fetchone())#只獲取一條數據
print(cur.description)#獲取表裏全部字段信息
cur.close()#關閉遊標
conn.close()#關閉數據庫
View Code
import hashlib, pymysql, datetime
def my_db(sql):
    import pymysql
    coon = pymysql.connect(
    host='118.24.3.40', user='jxz', passwd='123456',
    port=3306, db='jxz', charset='utf8')
    cur = coon.cursor()  # 創建遊標
    cur.execute(sql)  # 執行sql
    if sql.strip()[:6].upper() == 'SELECT':
        res = cur.fetchall()
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res
def my_md5(str):
    import hashlib
    new_str = str.encode()  # 吧字符串轉成bytes類型
    m = hashlib.md5()  # 實例化md5對象
    m.update(new_str)  # 加密
    return m.hexdigest()  # 獲取返回結果
def reg():
    username = input("username:").strip()
    pwd = input("pwd:").strip()
    cpwd = input('cpwd:').strip()
    if username and pwd and cpwd:
        sql = 'select * from nhy where name = "%s";' % username
        res = my_db(sql)
        if res:
            print("該用戶已經存在!")
        else:
            if pwd == cpwd:
                md5_pwd = my_md5(pwd)
                insert_sql = 'insert into nhy (name,pwd) values ("%s","%s");' % (username, md5_pwd)
                my_db(insert_sql)
                print("註冊成功!")
            else:
                print('兩次輸入的密碼不一致!')
    else:
        print('必填項不能爲空!')
def login():
    username = input('username:').strip()
    pwd = input('pwd:').strip()
    if username and pwd:
        md5_pwd = my_md5(pwd)
        sql = 'select * from nhy where name = "%s" and pwd = "%s";' % (username, md5_pwd)
        res = my_db(sql)
        if res:
            print("歡迎,登錄成功!今天是%s" % datetime.date.today())
        else:
            print('帳號或密碼錯誤')
    else:
        print("必填項不能爲空!")
# login()
reg()
數據庫練習

5.時間模塊

1.time模塊提供各類時間相關的功能,與時間相關的模塊有:time,datetime,calendar等。

2.時間有三種表示方式,一種是時間戳、格式化時間、時間元組。時間戳和格式化時間相互轉化,都須要先轉化爲時間元祖,時間戳單位最適於作日期運算。

import datetime,time
ticks = time.time()
print('當前時間戳:',ticks)#當前的時間戳
a = time.strftime('%Y-%m-%d %H:%M:%S')  #當前時間表示
print(a)
time.sleep(30)#等待30秒
time1 = time.strptime('2038-08-29 19:23:59','%Y-%m-%d %H:%M:%S')#時間格式
b = time.mktime(time1)#時間元祖轉換爲時間戳
start=1535731200#利用time包的函數localtime將其轉換爲日期。
start_trans=time.localtime(start)
print(start_trans)
#時間戳轉格式日期須要的格式。如(%Y-%m-%d %H:%M:%S)
start_trans_2=time.strftime('%Y-%m-%d %H:%M:%S',start_trans)
print(start_trans_2)
start_trans_3=time.strftime('%Y-%m-%d',start_trans)
print(start_trans_3)
#把時間格式轉換爲員組
now = '2019-09-11 00:00:00'
now = time.strptime(now,"%Y-%m-%d %H:%M:%S")
#將標準時間格式轉換爲時間戳
now_a = time.mktime(now)
print(now)
print(now_a)
time模塊

 5.glob 模塊

import glob
'''glob 模塊是查找文件路徑的模塊,支持*?[]這三種通配符,返回的數據類型是list.
* 表明0個或多個字符
? 表明一個字符
[]匹配指定範圍內的字符,如[0 - 9]匹配數字, 也可使用!表明不匹配的'''
glob1 = glob.glob(r"/Users/my_python/*.py")
# 過濾,只搜索以py結尾的文件。
print(glob1)

glob2 = glob.glob(r"/Users/my_python/0?.py")
print(glob2)

glob3 = glob.glob(r"/Users/my_python/0[0,1,2].py")
print(glob3)

glob4 = glob.glob(r"/Users/my_python/0[0-3].py")
print(glob4)

glob5 = glob.glob(r"/Users/my_python/0[a-z].py")
print(glob5)
glob模塊

6.OS模塊

os模塊:負責程序與操做系統的交互,提供了訪問操做系統底層的接口;

import os
os.remove('filename')# 刪除文件
os.rename(oldname, newname) #重命名文件
os.walk() #生成目錄樹下的全部文件名
os.chdir('dirname')# 改變目錄
os.mkdir/makedirs('dirname')#建立目錄/多層目錄
os.rmdir/removedirs('dirname')# 刪除目錄/多層目錄
os.listdir('dirname') #列出指定目錄下的全部文件
os.getcwd() #取得當前工做目錄
os.chmod() #改變目錄權限
os.path.basename('path/filename') #去掉目錄路徑,返回文件名
os.path.dirname('path/filename') #去掉文件名,返回目錄路徑
os.path.join(path1[,path2[,...]]) #將分離的各部分組合成一個路徑名
os.path.split('path')# 返回( dirname(), basename())元組
os.path.splitext() #返回 (filename, extension) 元組
os.path.getatime\#ctime\mtime 分別返回最近訪問、建立、修改時間
os.path.getsize() #返回文件大小
os.path.exists() #是否存在
os.path.isabs() #是否爲絕對路徑
os.path.isdir() #是否爲目錄
os.path.isfile() #是否爲文件
os模塊

7.sys模塊

負責程序與python解釋器的交互,提供了一系列的函數和變量,用於操控python的運行時環境。

import sys
sys.argv #命令行參數List,第一個元素是程序自己路徑
sys.modules.keys() #返回全部已經導入的模塊列表
sys.exc_info()# 獲取當前正在處理的異常類,exc_type、exc_value、exc_traceback當前處理的異常詳細信息
sys.exit(n)# 退出程序,正常退出時exit(0)
sys.hexversion #獲取Python解釋程序的版本值,16進制格式如:0x020403F0
sys.version #獲取Python解釋程序的版本信息
sys.maxint #最大的Int值
sys.maxunicode #最大的Unicode值
sys.modules #返回系統導入的模塊字段,key是模塊名,value是模塊
sys.path #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform #返回操做系統平臺名稱
sys.stdout #標準輸出
sys.stdin 3標準輸入
sys.stderr #錯誤輸出
sys.exc_clear() #用來清除當前線程所出現的當前的或最近的錯誤信息
sys.exec_prefix #返回平臺獨立的python文件安裝的位置
sys.byteorder #本地字節規則的指示器,big-endian平臺的值是'big',little-endian平臺的值是'little'
sys.copyright #記錄python版權相關的東西
sys.api_version# 解釋器的C的API版本
sys模塊

 8.發送郵件模塊  yagmil

import yagmail
user='xxx@163.com'
password='xxxxxxxxxx'
m = yagmail.SMTP(host='smtp.163.com',user=user,password=password,)
#smtp.qq.com,smtp_ssl=True 若是是qq郵箱的話加這個參數
m.send(to=['xxxxxx@qq.com'],
       #多個用戶發送能夠直接在後面加郵箱地址"ddd@aa.com",也能夠用list列表
       subject='明天不上課',contents='明天不上課,在家好好休息。。。', )
#to 表示接收的郵箱號,subject表示:標題,  contents 表示:內容,
View Code

9.打印日誌模塊  nnlog

import nnlog
log = nnlog.Logger(file_name='my.log', level='debug', when='D', backCount=5, interval=1)
# file_name是日誌文件名
# level是日誌級別,若是不傳的話默認是debug級別:(error錯誤,waing警告,info打印提示信息,debug調試信息)
# when是日誌文件多久生成一個,默認是按天,S 秒、M 分、 H 小時、 D 天、 W 每星期
# backCount是備份幾個日誌文件,默認保留5天的
# interval是間隔多久生成一個日誌文件,默認是1天
log.debug('默認日誌級別是debug')
log.info('info級別')
log.warning('waring級別')
log.error('error級別')
#error級別是最高的其餘就不顯示了,
log2 = nnlog.Logger(file_name='nn.log')  # 直接傳入文件名也是ok的,其餘的就取默認值了
log2.debug('test')
View Code

10.random隨機模塊

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)  # 全部的數字和字母
View Code

 11. requests模塊

requests模塊是python的一個第三方模塊,它是基於python自帶的urllib模塊封裝的,用來發送http請求和獲取返回的結果,操做很簡單。須要本身安裝  pip install requests

import requests
req = requests.get('http://www.baidu.cn',data={'username':'xxx'},cookies={'k':'v'},
                   headers={'User-Agent':'Chrome'},verify=False,timeout=3)  #發送get請求,data是請求數據,
            # cookies是要發送的cookies,headers是請求頭信息,verify=False是https請求的時候要加上,要否則會報錯。
            #timeout參數是超時時間,超過幾秒鐘的話,就再也不去請求它了,會返回timeout異常
req3 = requests.put('http://www.baidu.cn') #put方式請求
req4 = requests.patch('http://www.baidu.cn')#patch方式請求
req5 = requests.delete('http://www.baidu.cn')#delete方式請求
req6 = requests.options('http://www.baidu.cn')#options方式請求,用法和上面的get、post都同樣

r = requests.get("https://www.baidu.com/")# get 請求獲取狀態碼
rl = requests.get(url='https://www.baidu.com/', params={'wd':'python'})  #帶參數的請求
url = 'http://www.baidu.com'
print(r.status_code) #獲取返回狀態碼,若是不是200,可使用r.raise_for_status() 拋出異常
print(r.recontent)#獲取返回的內容,二進制格式,通常下載圖片、視頻用這個
print(r.text) #獲取返回的內容,字符串格式
print(r.json())#獲取返回的內容,json格式,這個必須是返回的是json纔可使用,不然會報錯
print(r.headers)#獲取響應頭
print(r.cookies)#獲取返回的cookie
print(r.encoding)#獲取返回的字符集
print(r.url)  #直接打印請求
print(r.content) #以字節流形式打印
View Code

練習題:下載音樂,先去查找音樂的url

 

import requests
MP3_url='https://m10.music.126.net/20190516150501/8b05e322544b18e336895e2bce407bfd/ymusic/0f0b/025c/5552/8acb80fd605655b99bfdb833e8478119.mp3'
res = requests.get(MP3_url)
mp3 = res.content  #返回的二進制內容
f = open('d12.mp3','wb')
f.write(mp3)
f.close() 
View Code
相關文章
相關標籤/搜索