Python經常使用模塊

1.標準模塊
python自帶,無需安裝,直接import就能夠用的模塊,例如json,datetime,os等
2.第三方模塊
別人寫好的模塊,本身安裝完就能用
   安裝方式:
a.傻瓜安裝,pip源,pip install name 若是電腦安裝python2和python3,則使用命令python3 -m pip install pymysql
b.手動安裝,官網下載whl文件,pip install /Users/chrislee/Downloads/redis-2.10.6-py2.py3-none-any.whl
c.手動安裝,官網下載tar文件,壓縮找到setup.py 執行 python setup.py install
3.本身寫的模塊
  放到python環境變量裏,就可直接import導入
4.如何調用

import module 調用時 module.func.
from module import func 調用時 func.

1、OS模塊
import os
print(os.getcwd())#獲取當前路徑
print(os.listdir())#列出當前目錄文件和文件夾
os.mkdir(r'D:\code-pratice\xiaona-pratice\test')#建立文件夾,不能遞歸,父目錄不存在則報錯
os.makedirs(r'D:\code-pratice\xiaona-pratice\test11\aaa')#建立文件夾,能夠遞歸,目錄不存在則會建立
print(os.sep)#輸出系統路徑分隔符
print(os.linesep)#輸出換行符
print(os.pathsep)
os.rmdir(r'D:\code-pratice\xiaona-pratice\test')#刪除空文件夾
os.remove('code')#刪除文件
print(os.path.join('code','aaa.txt'))#鏈接路徑
print(os.path.dirname(r'D:\code-pratice\xiaona-pratice\test'))#提取父目錄路徑
print(os.path.basename(r'D:\code-pratice\xiaona-pratice\test'))#獲取文件名
print(os.path.exists('day4'))#判斷文件或者文件夾是否存在
print(os.path.isdir('day5'))#判斷是否爲文件夾
print(os.path.isfile('day5'))#判斷是否爲文件
print(os.path.split(r'D:\code-pratice\xiaona-pratice\test'))#把文件和路徑分開,返回list
print(os.walk(r'D:\code-pratice\xiaona-pratice\test11'))#列出全部的目錄,目錄下文件夾、文件
print(os.getcwd())
print(os.path.abspath('.'))#取絕對路徑
print(os.path.abspath('..'))#取上一級目錄
print(os.path.abspath('../day7'))#取上一級目錄的day7
print(os.listdir())
os.chdir('../day3')#改變目錄
print(os.getcwd())
os.system('ifconfig')#用來執行操做系統命令
os.system('top')
res = os.system('ls')#只能執行,獲取不到結果
print('res=',res)#返回0  則表明命令執行成功 1 爲不成功
res = os.popen('ls').read()#不只能夠執行命令 還能夠獲取到結果
print('res= ',res)
動態的結果 好比top  沒法執行popen()
res = os.popen('top -n 1').read()
print('res= ',res)

小練習1:建立10個文件夾python

for i in range(10):
    os.mkdir(r'D:\code-pratice\xiaona-pratice\test11\new%s'%i)#建立10個文件夾

小練習2:給末尾爲偶數的文件夾中建立a.txt文件,並向文件中寫點數據(下面代碼test11中沒有偶數結尾的文件,若有則如下代碼不知足)mysql

import os
dirs = os.listdir(r'D:\code-pratice\xiaona-pratice\test11')#列出全部的文件夾和文件
print(dirs)
for dir in dirs:
    if dir[-1].isdigit():
        if int(dir[-1])%2==0: 
            with open(r'D:\code-pratice\xiaona-pratice\test11\%s\a.txt'%dir,'a+',encoding='utf-8') as f:
                f.write("隨便寫點啥qwertyui")

小練習3:給全部log日誌中的文件後綴加上.bak         'D:\code-pratice\\xiaona-pratice\day5\day5\logs' 這個目錄下有文件夾,文件夾下有log日誌git

import os
for cur_dir,dirs,files in os.walk(r'D:\code-pratice\xiaona-pratice\day5\day5\logs'):
    for f in files:
        old_name = os.path.join(cur_dir,f)#拼接成絕對路徑
        new_name = os.path.join(cur_dir,f+'.bak')
        os.rename(old_name,new_name)#絕對路徑修更名字

 2、time&datetime模塊redis

時間戳 從unix元年開始到如今過的秒數算法

import time
print(time.time())#獲取當前時間戳
print(int(time.time()))#時間戳取整
print(time.strftime('%Y-%m-%d %H-%M-%S'))
print(time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='',m='',d='',h='',f='',s=''))
print(time.gmtime())#把時間戳轉爲時間元祖,若是不傳時間,則取標準時區,與中國時區差8小時
print(time.localtime())#也是將時間戳轉爲元祖,不傳則取當地時區
print(time.asctime())#將元祖轉爲格式化的時間
print(time.strftime('%Y-%m-%d %H-%M-%S',yuanzu))#按指定格式
print(time.strptime('20180701','%Y%m%d'))#將格式化好的時間轉爲時間元祖
print(time.mktime(tuple))#將元祖轉爲時間戳
print(datetime.datetime.now())#當前格式化的時間
print(datetime.datetime.now()+datetime.timedelta(3))#3天后的時間
print(datetime.datetime.now()+datetime.timedelta(-3))#3天前的時間

小練習1:獲取3天前的日期sql

import time
# 將時間戳轉爲時間元祖gmtime 或者localtime
# 再將時間元祖轉爲格式化好的時間asctime
timestamp= int(time.time())-3*24*3600#獲取3天前的時間戳
time_tuple = time.localtime(timestamp)#將時間戳轉爲時間元祖
print(time.strftime('%Y-%m-%d %H-%M-%S',time_tuple))#時間元祖轉爲指定格式的時間

小練習2:寫一個時間戳轉爲格式化時間的函數json

import time
def
timestampToStr(timestamp=None,format='%Y-%m-%d %H-%M-%S'): if timestamp: time_tuple = time.localtime(timestamp)#時間戳轉爲時間元祖 return time.strftime(format,time_tuple)#時間元祖轉爲格式化後的時間 else: return time.strftime(format)#不傳時間戳,則取當前時間

小練習3:寫一個格式化時間轉爲時間戳的函數服務器

import time
def strToTimestamp(format_time=None,format='%Y-%m-%d %H-%M-%S'):

    if format_time:
        time_tuple = time.strptime(format_time,format)
        return int(time.mktime(time_tuple))
    else:
        return int(time.time())#不傳時間,則取當前時間

 3、datetime模塊函數

import datetime
print(datetime.date.today())#當天的年月日
print(datetime.datetime.today())#當天的年月日時分秒
print(datetime.date.today()+datetime.timedelta(-1))#一天前
print(datetime.datetime.today()+datetime.timedelta(hours=10))#10個小時以後
res = datetime.datetime.today()+datetime.timedelta(hours=10,minutes=20,seconds=30)#10個小時,20分組,30秒以後
print(type(res))
print(res.today())#取到日期
print(res.time())#取到時間
print(res.timestamp())#取到時間戳
print(res.strftime('%Y-%m-%d %H:%M:%S'))#格式化時間

4、nnlog模塊ui

第三方模塊,須要安裝

import nnlog
log = nnlog.Logger(file_name='mylog',level='debug',when='D',backCount=5,interval=1)

log.debug('默認日誌級別是debug')
log.info('info級別')
log.warning('warning級別')
log.error('error級別')
log2 = nnlog.Logger(file_name='nn.log')
log2.debug('test')

 5、hashlib加密模塊

import hashlib
s = 'djdshshsh'
#md5加密算法
m = hashlib.md5(s.encode())#s.encode()字符串轉爲byte類型
print(m.hexdigest())#獲取加密後的結果
#md5加密不可逆,不能解密
#撞庫(md5在線解密),存有經常使用的md5加密後的數據,複雜的就沒法查到
m1 = hashlib.sha224(s.encode())#也是一種加密的算法,長度不同
print(m1.hexdigest())

 6、yagmail模塊

import yagmail
#帳號 密碼 郵件服務器 收件人 抄送人 主題 正文 附件
username = '1020564551@qq.com'
passwd = 'xxxxxxxxxxxx'#用的是受權碼,通常公司的郵件沒有受權碼就用本身的郵箱密碼
#qq郵箱要加上smtp_ssl=True
#鏈接上郵箱
mail = yagmail.SMTP(user=username,password=passwd,host='smtp.qq.com',smtp_ssl=True)
# mail.send(to=['chrislina1115@163.com','caoyu@tom.com'],cc='382593772@qq.com',
#           subject='python自動發郵件嘗試',contents='吃飯了嗎,成功了嗎',
#           attachments='/Users/chrislee/Downloads/產品.json')
mail.send(to='chrislina1115@163.com',
          subject='python自動發郵件嘗試',contents='吃飯了嗎,成功了嗎',
          attachments='/Users/chrislee/Downloads/產品.json')

 7、xlwt模塊(只能寫)

import xlwt
book = xlwt.Workbook()#建立excel
sheet = book.add_sheet('stu_info')#增長sheet頁
sheet.write(0,0,'學生編號')#行,列
sheet.write(0,1,'學生姓名')#行,列
sheet.write(0,2,'成績')#行,列
sheet.write(1,0,'1')#行,列
sheet.write(1,1,'lina')#行,列
sheet.write(1,2,'98.88')#行,列
book.save('stu.xls')#必定要用xls,不能用xlxs(會打不開)

  8、xlrt模塊

import xlrd
book = xlrd.open_workbook('stu.xls')
sheet = book.sheet_by_index(0)
print(sheet.cell(0,0).value)#只能行列,獲取某個單元格的內容
print(sheet.row_values(0))#獲取第一行數據
print(sheet.nrows)#excel總共有多少行
print(sheet.col_values(0))#獲取第一列數據
print(sheet.ncols)#總共有多少列

練習:修改excel數據

import xlrd
from xlutils import copy
book = xlrd.open_workbook('stu.xls')#打開原來的excel
new_book = copy.copy(book)
sheet = new_book.get_sheet(0)#獲取一個sheet頁
sheet.write(1,3,'18')
sheet.write(1,1,'lina')
new_book.save('stu.xls')
相關文章
相關標籤/搜索