python 基礎筆記——常用模組

codelife發表於2019-08-25

import(modulename):匯入模組

math

>>> import math

1、向上取整

math.ceil()

>>> num = 3.14
>>> math.ceil(num)
4

2、向下取整

math.floor()

>>> num = 5.9
>>> math.floor(num)
5
#或
>>> int(num)
5

datetime

>>>from datetime import datetime

1、獲取當前格式化日期

>>> print(datetime.now())
2017-09-30 09:12:31.070312

2、獲取指定日期和時間

>>> dt = datetime(2017, 10, 1, 6, 30)
>>> print(dt)
2017-10-01 06:30:00

3、把格式化時間轉換為時間戳。python的tempstamp是一個浮點數。小數位表示毫秒數

>>> dt = datetime(2017, 9, 30, 9, 48)
>>> dt.timestamp()
1506736080.0

4、格式化時間戳

>>> t = 1506736080.0
>>> print(datetime.fromtimestamp(t))
2017-09-30 09:48:00
注:datetime.utcfromtimestamp(t):直接轉換到utc標準時區的時間

5、datetime轉換為str

>>> now = datetime.now()
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2018-03-03 22:06:44'

6、datetime加減

>>> from datetime import datetime, timedelta

>>> now = datetime.now()
>>> print(now)
2017-09-30 10:36:54.148904
>>> print(now + timedelta(hours=1))
2017-09-30 11:36:54.148904
>>> print(now + timedelta(days=1))
2017-10-01 10:36:54.148904
>>> (datetime.now()-timedelta(days=1, hours=1, minutes=1, seconds=1)).strftime('%Y-%m-%d %H:%M:%S')
'2018-03-02 21:15:24'

7、datetime.now().timetuple()

返回當前時間struct_time格式

>>> datetime.now().timetuple()
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=19, tm_min=45, tm_sec=29, tm_wday=6, tm_yday=274, tm_isdst=-1)

8、datetime.now().replace()

傳入的引數會替換結果時間,如果什麼都沒傳,則返回撥用replace()的時間物件

>>> datetime.now().replace(2017,10,1)
datetime.datetime(2017, 10, 1, 19, 49, 53, 838155)

time

>>>import time

1、time.localtime()

>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=30, tm_hour=11, tm_min=28, tm_sec=1, tm_wday=5, tm_yday=273, tm_isdst=0)
索引(index) 屬性(attribute) 值(values)
0 tm_year(年) 2017
1 tm_mon(月) 1-12
2 tm_mday(日) 1-31
3 tm_hour(時) 0-23
4 tm_min(分) 0-59
5 tm_sec(秒) 0-59
6 tm_wday(周) 0-6(0是週日)
7 tm_yday 一年中第幾天
8 tm_isdst(夏令制)

2、time.sleep(second):讓程式暫停second秒後執行

3、time.time():返回當前時間戳

>>> time.time()
1506742662.695589

4、獲取格式化時間

>>> print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
2017-09-30 11:41:21

5、time.clock():

該函式有兩個功能,

在第一次呼叫的時候,返回的是程式執行的實際時間;

以第二次之後的呼叫,返回的是自第一次呼叫後,到這次呼叫的時間間隔

在win32系統下,這個函式返回的是真實時間(wall time),而在Unix/Linux下返回的是CPU時間。

6、指定日期轉換為時間戳

import time
t = "2017-11-24 17:30:00"
#將其轉換為時間陣列
timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S")
#轉換為時間戳:
timeStamp = int(time.mktime(timeStruct))
print(timeStamp)
#結果:
1511515800

7、指定時間戳格式化

timeStamp = 1511515800
localTime = time.localtime(timeStamp)
strTime = time.strftime("%Y-%m-%d %H:%M:%S", localTime)
print(strTime)
結果:
2017-11-24 17:30:00

sys

>>>import sys

1、sys.argv

獲取傳入指令碼的引數,第一個引數是指令碼本身

test.py
print(sys.argv)
F:\python\test>python test.py 1 2 3
['test.py', '1', '2', '3']

2、sys.path

返回模組的搜尋路徑,從當前檔案所在路徑開始搜尋

>>> sys.path
['', 'D:\\Software\\python36.zip', 'D:\\Software\\DLLs', 'D:\\Software\\lib', 'D:\\Software', 'D:\\Software\\lib\\site-packages']

3、sys.version

返回python版本資訊

>>> sys.version
'3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]'

4、sys.exit()

退出程式,和exit()功能一樣

>>> sys.exit('good bye')
good bye
C:\Users\HONOUR-CYY>

5、sys.platform

返回作業系統平臺名稱

>>> sys.platform
'win32'

6、sys.stdout.write(str)

在螢幕上列印資料

>>> sys.stdout.write('hello')
hello
>>> sys.stdout.write('\r') #重新整理之前輸出到螢幕的內容

7、sys.stdout.flush()

重新整理緩衝區的內容到螢幕

pickle

序列化:把變數從記憶體中變成可儲存或傳輸的過程稱之為序列化

>>>import pickle

1、pickle.dumps()

把任意物件序列化成一個bytes,

>>> d = dict(name='chenyy', age=20)
>>> a = pickle.dumps(d)
>>> a
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x06\x00\x00\x00chenyyq\x02X\x03\x00\x00\x00ageq\x03K\x14u.'

pickel.dump():直接把一個序列化物件寫入檔案

>>> f = open('dump.txt', 'wb')
>>> pickle.dump(d, f)
>>> f.close()

2、pickel.loads()

反序列化出物件

>>> pickle.loads(a)
{'name': 'chenyy', 'age': 20}

pickle.load():方法從一個file-like Object中直接反序列化出物件

>>> f = open('dump.txt', 'rb')
>>> d pickle.load(f)
>>> f .close()
>>> d
{'name': 'chenyy', 'age': 20}

json

>>> import json

1、json.dumps()

把物件轉化為一個字串

>>> d = dict(name='chenyy', age=18)
>>> json.dumps(d)
'{"name": "chenyy", "age": 18}'
json.dump()方法可以直接把json寫入一個file-like Object

2、json.loads()

把json反序列化為python物件

>>> json_str = json.dumps(d)
>>> json.loads(json_str )
{'name': 'chenyy', 'age': 18}

json.load()方法從file-like Object中讀取字串並反序列化

os

1、os.getcwd()

獲取當前工作目錄

>>> os.getcwd()
'C:\\Users\\HONOUR-CYY'

2、os.chdir(dir)

改變當前指令碼工作目錄

>>> os.chdir('D:')
>>> os.getcwd()
'D:\\'

3、os.pardir

返回當前目錄的父目錄('..')

>>> os.pardir
'..'

4、os.curdir

返回當前目錄('.')

>>> os.curdir
'.'

5、os.makedirs(dir)

遞迴生成多層目錄

>>> os.makedirs('a/b/c')

6、os.removedirs(dir)

遞迴向上刪除空目錄。如果目錄非空則丟擲異常

>>> os.removedirs('D:/a/b/c')

7、os.mkdir(dir)

生成目錄

os.mkdir('b')

8、os.rmdir(dir)

刪除一個空目錄

9、os.listdir()

返回指定目錄下的所有檔案和子目錄,包括隱藏檔案,以列表形式返回。只會獲取一層

10、os.remove(file)

刪除一個檔案

11、os.rename('oldname','newname')

重新命名檔案或目錄

12、os.stat()

獲取檔案或目錄資訊

>>> os.stat('./d.txt')
os.stat_result(st_mode=33206, st_ino=562949953466137, st_dev=462496, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1506996315, st_mtime=1506996321, st_ctime=1506996315)

13、os.sep

返回作業系統特定的分隔符,win下為'\',Linux下為‘/’

>>> os.sep
'\\'

14、os.linesep

返回作業系統的行終止符win下為"\r\n",Linux下為"\n"

>>> os.linesep
'\r\n'

16、os.name

返回當前作業系統

win:
>>> os.name
'nt'
linux:
>>> os.name
'posix'

17、os.system(command)

可以用來直接執行shell命令

>>> os.system('tree')
卷 文件 的資料夾 PATH 列表
卷序列號為 0000008E 0007:0EA0
E:.
└─d
└─b
└─c
0

18、os.environ

返回系統環境變數

19、os.path.abspath(path)

返回path規範化的絕對路徑

>>> os.path.abspath('./d.txt')
'E:\\test\\d.txt'

20、os.path.split(path)

將path分割成目錄和檔名,以元組返回

>>> os.path.split('D:/test/d.txt')
('D:/test', 'd.txt')
>>> os.path.split('F:/python/a')
('F:/python', 'a')

21、os.path.dirname(path)

返回path的目錄,即os.path.split(path)獲取的第一個元素

>>> os.path.dirname('D:/test/d.txt')
'D:/test'
>>> os.path.dirname('F:/python/a')
'F:/python'

22、os.path.basename(path)

返回os.path.split(path)獲取的第二個元素

>>> os.path.basename('D:/test/d.txt')
'd.txt'
>>> os.path.basename('F:/python/a')
'a'

23、os.path.exists(path)

判斷path是否存在,返回布林值

>>> os.path.exists('E:/test/d')
True
>>> os.path.exists('E:/test/d.txt'
True

24、os.path.isabs(path)

是否為絕對路徑,返回布林值

>>> os.path.isabs('E:/test/d.txt')
True
>>> os.path.isabs('./x.txt')
False

25、os.path.isfile(file)

判斷檔案是否存在,返回布林值。目錄返回False

>>> os.path.isfile('./d.txt')
True

26、os.path.isdir(dir)

判斷目錄是否存在,返回布林值。檔案返回False

>>> os.path.isdir('./d')
True

27、os.path.join(path1[, path2...])

將多個路徑組合後返回

>>> os.path.join('/data','myproject','chenyy')
'/data/myproject/chenyy'

28、os.path.getatime(path)

返回path所指向的檔案或者目錄的最後存取時間,浮點數

>>> os.path.getatime('./d.txt')
1506996315.766825

29、os.path.getmtime(path)

返回path所指向的檔案或目錄的最後修改時間,浮點數

>>> os.path.getmtime('./d.txt')
1506996321.7812703

30、os.path.getctime(path)

返回path的建立時間,浮點數

>>> os.path.getctime('./d.txt')
1506996315.766825

31、os.path.getsize(file)

返回檔案大小,如果是目錄則返回0

>>> os.path.getsize('./d.txt')
12
>>> os.path.getsize('./d')
0

32、os.path.splitext(file)

>>> os.path.splitext('log.text')
以元組形式返回檔名和字尾
('log', '.text')

33、os.startfile(path)

windows中特有的函式,啟動外部程式

hashlib

>>> import hashlib
>>> md5 = hashlib.md5()
>>> md5.update('123456'.encode('utf-8'))
>>> md5.hexdigest()
'e10adc3949ba59abbe56e057f20f883e'
如果資料量很大,可以分塊多次呼叫update(),最後計算的結果是一樣的:
>>> md5 = hashlib.md5()
>>> md5.update('123'.encode('utf-8'))
>>> md5.update('456'.encode('utf-8'))
>>> md5.hexdigest()
'e10adc3949ba59abbe56e057f20f883e'

configparser

解析配置檔案(假設有個ini的配置檔案,內容如下)

[cyy]
age = 18
name = cyy
[chenyy]
age : 24
name : chenyy

>>> import configparser
>>> con = configparser.ConfigParser()
>>> con.read('ini', encoding='utf-8')
['ini']

con.sections()

獲取所有節點

>>> con.sections()
['cyy', 'chenyy']

con.options(section)

獲取指定節點下所有鍵

>>> con.options('cyy')
['age', 'name']

con.items(section)

獲取指定節點下所有鍵值對

>>> con.items('chenyy')
[('age', '24'), ('name', 'chenyy')]

con.get(section,key)

獲取指定節點下指定鍵對應的值

>>> con.get('chenyy','age')
'24'
con.getint(section,key) #把返回的值轉換為整型
con.getfloat(section,key) #把返回的值轉換為浮點型
con.getboolean(section,key) #把返回的值轉換為布林型

con.has_section(section)

檢查節點是否存在,返回布林值

>>> con.has_section('abc')
False
>>> con.has_section('cyy')
True

con.add_section(section)

con.write(open(file,'w'))

新增節點

>>> con.add_section('abc')
>>> con.write(open('ini','w'))

con.remove_section(section)

con.write(open(file,'w'))

刪除節點,返回布林值,刪除成功後需要寫入儲存

>>> con.remove_section('abc')
True
>>> con.write(open('ini','w'))

con.has_option(section,key)

檢查節點下的key是否存在,返回布林值

>>> con.has_option('cyy','age')
True

con.set(section,key,value)

con.write(open(file,'w'))

設定指定節點下的鍵值對

>>> con.set('chenyy','name','chenyy')
>>> con.write(open('ini','w'))

con.remove_option(section,key)

con.write(open(file,'w'))

刪除指定節點下的鍵,返回布林值,刪除成功後需要寫入檔案儲存

>>> con.remove_option('chenyy','name')
True
>>> con.write(open('ini','w'))

shutil

檔案、資料夾、壓縮包處理模組

>>> import shutil

1、shutil.copyfileobj(oldfile_object,newfile_object)

將檔案內容複製到另一個檔案中

>>> import shutil
>>> shutil.copyfileobj(open('ini','r'),open('new','w'))

2、shuutil.copyfile(filepath,filepath)

複製檔案,檔案不存在則建立

>>> shutil.copyfile('d.txt','./d/d.txt')
'./d/d.txt'

3、shutil.copymode()

僅複製許可權,內容,組,使用者均不變

4、shutil.copystat()

僅複製檔案的狀態資訊,包括:mode bits, atime, mtime, flags

5、shutil.copy()

複製檔案和許可權

6、shutil.copy2()

複製檔案和狀態

7、shutil.copytree(olddir, newdir, symlinks=False, ignore=None)

遞迴複製目錄下的所有檔案和資料夾,newdir不存在則建立

引數ignore=shutil.ignore_patterns(pattern),代表不複製正則匹配項匹配到的檔案或目錄

8、shutil.rmtree(dir)

遞迴刪除目錄下的所有檔案和資料夾

9、shutil.move(olddir, newdir)

遞迴移動目錄,也可重新命名目錄,類似linux的mv

10、shutil.make_archive(filename, format, root_dir,owner,group)

壓縮檔案,返回壓縮後的壓縮包絕對路徑

filename:壓縮包的檔名,可以指定路徑

format:壓縮包種類,zip,tar,bztar,gztar

root_dir:需要壓縮檔案的路徑

owner:使用者,預設當前使用者、

group:組,預設當前組

>>> shutil.make_archive('../www','gztar',root_dir='./o')
'E:\\www.tar.gz'

zipfile

>>> import zipfile

壓縮檔案

z = zipfile.ZipFile(zipname,format)

z.write(filename)

z.close()

format:檔案寫入模式,'w', 'a'。w方式會清空壓縮包裡的所有內容

>>> import zipfile
>>> z = zipfile.ZipFile('test.zip', 'a')
>>> z.write('./d.txt') #如果寫入一個目錄則只會寫入一個空目錄,不會寫入該目錄下其它檔案或資料夾
>>> z.close()

解壓檔案

z = zipfile.ZipFile(zipname,format)

z.extractall()

z.close()

解壓過後壓縮包檔案仍然在

>>> zip = zipfile.ZipFile('./test.zip','r')
>>> zip.extractall()
>>> zip.close()

z = zipfile.ZipFile(zipname,format)

z.namelist()

z.close()

以列表返回壓縮包裡的所有檔案和目錄

>>> z = zipfile.ZipFile('test.zip','r')
>>> z.namelist()
['new', 'd/']

z = zipfile.ZipFile(zipname,format)

z.extract(file)

z.close()

解壓壓縮包裡的指定檔案或目錄

>>> z = zipfile.ZipFile('test.zip','r')
>>> z.extract('new')
'E:\\test\\new'
>>> z.close()

tarfile

>>> import tarfile

壓縮

tar = tarfile.open(tarname,format)
tar.add(filepath,arcname=alias)
tar.close()
#arcname:把檔案壓縮排壓縮包後可以換個檔名
#解壓
tar = tarfile.open(tarname,format)
tar.extractall()
tar.close()

logging

記錄日誌
>>> import logging

logging.basicConfig(
    filename='log.log',
    format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    level=logging.INFO
)
#level:日誌等級
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

logging.critical()
logging.fatal()
logging.error()
logging.waring()
logging.info()
logging.debug()

collections

namedtuple(name,[屬性list])

namedtuple是一個函式,它用來建立一個自定義的tuple物件,並且規定了tuple元素的個數,並可以用屬性而不是索引來引用tuple的某個元素

>>> from collections import namedtuple
>>> P = namedtuple('Point', ['x', 'y'])
>>> p = P(1, 2)
>>> p.x
1
>>> p.y
2

deque

使用list儲存資料時,按索引訪問元素很快,但是插入和刪除元素就很慢了,因為list是線性儲存,資料量大的時候,插入和刪除效率很低。

deque是為了高效實現插入和刪除操作的雙向列表,適合用於佇列和棧

>>> from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.append('d')
>>> q.appendleft('o')
>>> q
deque(['o', 'a', 'b', 'c', 'd'])

deque除了實現list的append()和pop()外,還支援appendleft()和popleft()

defaultdict

defaultdict建立的字典在引用的key不存在時返回一個預設值

>>> from collections import defaultdict
>>> dd = defaultdict(lambda: 'N/A')
>>> dd['key1'] = 'a'
>>> dd['key1']
'a'
>>> dd['key2']
'N/A'

OrderedDict

OrderedDict會根據插入key的順序排序

>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['a'] = 1
>>> od['c'] = 2
>>> od['b'] = 3
>>> od
OrderedDict([('a', 1), ('c', 2), ('b', 3)])

itertools

chain()

chain()可以把一組迭代物件串聯起來,形成一個更大的迭代器

>>> import itertools
>>> for i in itertools.chain('abc', 'xyz', 'def'):
... print(i)
...
a
b
c
x
y
z
d
e
f
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章