Skip to main content

Module

Datetime模組

  • 處理日期跟時間有關的模組
import datetime
x = datetime.datetime(2018,6,1)
print(x.strftime("%Y-%m+%d")) #2018-06-01

from datetime import datetime as dt
print(dt.now()) #目前日期時間

import datetime
today = datetime.datetime.today()
print(today) #今天
print(today.strftime("%Y-%m-%d %H:%M:%S")) #格式化日期
print("現在是 {}年{}月{}日".format(today.year,today.month,today.day))

Math模組

  • 處理與數學計算有關的模組
import math
x1 = math.ceil(1.4)
x2 = math.floor(1.4)
x3 = math.sqrt(64)
x4 = math.sin(0)
x5 = math.cos(0)

Random模組

  • 產生隨機亂數的模組
  • 可以加上seed讓每次的結果一樣
import random
random.seed(10) //讓每次的random都一樣,比較好debug
print(random.random())
print(random.randrange(3,9)) //隨機在39之間產生數字

mylist = ['apple','banana','cherry']
random.shuffle(mylist) //洗牌的動作
print(mylist)
print(random.sample(mylist,k=2)) //隨機取2
print(random.choices(mylist,weights=[10,1,1], k=10)) //權重10在apple,1在banana,1在cherry之後隨機取10

OS模組

  • OS模組是用來處理跟作業系統有關的模組
import os
os.getcwd() //current working directory 當前資料夾路徑
path = os.environ.get('PATH') //取得環境變數內容
home = os.path.expanduser('~') //取得家目錄路徑
os.listdir(path) //path路徑下的所有檔案及資料夾
os.path.exists('hello.py') //資料夾是否存在
os.path.isfile('hello.py') //檔案是否存在
os.rename('test1.txt','test2.txt') //重新命名檔案
os.remove('test2.txt') //移除檔案
os.mkdir('myfolder') //建立資料夾

files = os.listdir('./files') //在路徑中蒐集所有檔案名稱
for i in files: //列出所有檔案
print(i)

Shutil模組

  • 用來處理檔案移動,複製,打包,壓縮,解壓的模組
import shutil
shutil.copytree('./thisfolder','./newfolder') #複製資料夾
shutil.rmtree('./newfolder') #刪除資料夾
shutil.copyfile('old.txt','new.txt') #拷貝檔案
shutil.move('new.txt','./thisfolder') #移動檔案到新位置

Json模組

  • 用來將json字串轉換成json物件
import json
x = '{"name":"John","age":30,"city":"New York"}' #x 是json字串
y.json.loads(x) #y 是json物件(也是一個字典)
print(y["age"]) #可以用字典的模式去存取它

person = {'name':'peter','age':25,'city':'taipei'} #一個json物件(也是一個字典)
mystring = json.dumps(person) #轉換成一個json格式的字串

print(json.dumps(['apple','banana'])) #list也可以轉換成json格式的字串
print(json.dumps(('apple','banana'))) #tuple也可以轉換成json格式的字串
print(json.dumps('hello')) #string也可以轉換成json格式的字串
print(json.dumps('45')) #int也可以轉換成json格式的字串
print(json.dumps('12.50')) #float也可以轉換成json格式的字串
print(json.dumps(True)) #bool也可以轉換成json格式的字串
print(json.dumps(None)) #null也可以轉換成json格式的字串

import json
inputfile = open('myfile.json')
jsonarray = json.load(inputfile) #可以取得json格式的內容
for item in jsonarray: #用迴圈去把它迭帶出來
print("id:" + item['id'])
print("name:" + item['name'])

Time模組

  • time模組可以返回當前時間
import time
print(time.time()) #以1970年1月1號0點開始算總共過了幾秒

begin = time.time() #開始時間
for i in range(10):
print('test', end=' ')
print('')
time.sleep(1) #休息1秒
end=time.time() #結束時間
print("總共花了{}秒".format(end-begin))

localtime = time.ctime(time.time()) #轉換為本地時間
print(localtime) #印出日期時間

t = time.localtime() #取得struct_time格式的時間
t2 = time.strftime("%Y-%m-%d %H:%M:%S",t) #印出2022-12-26 12:45:02

Sys模組

  • 可以讓程式內某些參數可以直接被直譯器存取
import sys
print(sys.argv[0]) #外部輸入的第1個參數
print(sys.argv[1]) #外部輸入的第2個參數

Zipfile模組

  • 可以對zip檔案進行壓縮或解壓縮
from zipfile import Zipfile
filename = "myfile.zip"
with Zipfile(filename,'r') as zip: #open zipfile in READ mode
zip.printdir() #print all contents of the zip file
print('Extracting all files now...')
zip.extractall() #extract all files
print('Done!')

Logging模組

  • 開發程式時常常寫一堆print,但實際部屬前則需要一一拿掉,Logging模組可以有更有效的方法
Logging可以分等級
import logging
logging.debug('debug message') #除錯
logging.info('info message') #訊息
logging.warning('warning message') #警告
logging.error('error message') #錯誤
logging.critical('critical message')#嚴重

print(logging.NOTSET) # 0
print(logging.DEBUG) # 10
print(logging.INFO) # 20
print(logging.WARNING) # 30
print(logging.ERROR) # 40
print(logging.CRITICAL) # 50

print(logging.geLevelName(0)) # NOTSET
print(logging.geLevelName(10)) # DEBUG
print(logging.geLevelName(20)) # INFO
print(logging.geLevelName(30)) # WARNING
print(logging.geLevelName(40)) # ERROR
print(logging.geLevelName(50)) # CRITICAL

import logging
for handler in logging.root.handlers[:]: #remove all handlers associated with the root logger object
logging.root.removeHandler(handler) #將前面的loggin設定都清乾淨
logging.basicConfig(level=logging.DEBUG) #比DUBUG等級更嚴重的才秀出來

#########################################################
import logging
FORMAT = '%(asctime)s %(levelname)s: %(message)s' #先設定好格式
logging.basicConfig(level=logging.DEBUG, format=FORMAT) #運用時間格式
logging.debug('debug message') # 2022-12-26 17:40:35,687 DEBUG: debug message
logging.info('info message') # 2022-12-26 17:40:35,687 INFO: info message
logging.warning('warning message') # 2022-12-26 17:40:35,687 WARNING: warning message
logging.error('error message') # 2022-12-26 17:40:35,687 ERROR: error message
logging.critical('critical message') # 2022-12-26 17:40:35,688 CRITICAL: critical message

logging.basicConfig(level=logging.DEBUG, filename='./mylog.log', filemode='w', format=FORMAT) #可以直接將log寫入檔案