python 常用模塊
常用模塊
calendar
time
datetime
timeit
os
shutil
zip
math
string
上述所有模塊使用理論上都應該先導入,string是特例
calendar,time,datetime的區別參考中文意思
calendar
跟日歷相關的模塊
# 使用需要先導入 import calendar
1
2
# calendar:獲取一年的日歷字符串 # 參數 # w = 每個日期之間的間隔字符數 # l = 每周所占用的行數 # c = 每個月之間的間隔字符數 cal = calendar.calendar(2017) print(type(cal))
1
2
3
4
5
6
7
1
cal = calendar.calendar(2017, l=0, c=5) print(cal)
1
2
2017 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 4 5 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19 16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26 23 24 25 26 27 28 29 27 28 27 28 29 30 31 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 7 1 2 3 4 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11 10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18 17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25 24 25 26 27 28 29 30 29 30 31 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 1 2 3 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30 31 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31 30 31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# isleap: 判斷某一年是否閏年 calendar.isleap(2000)
1
2
True
1
# leapdays: 獲取指定年份之間的閏年的個數 calendar.leapdays(2018, 1998)
1
2
-5
1
help(calendar.leapdays)
1
Help on function leapdays in module calendar: leapdays(y1, y2) Return number of leap years in range [y1, y2). Assume y1 <= y2.
1
2
3
4
5
# month()獲取某個月的日歷字符串 # 格式:calendar.month(年,月) # 返回值:月日歷的字符串 m3 = calendar.month(2018, 3) print(m3)
1
2
3
4
5
March 2018 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
1
2
3
4
5
6
7
# monthrange() 獲取一個月的周幾開始即和天數 # 格式:calendar.monthrange(年,月) # 返回值:元組(周幾開始,總天數) # 注意:周默認 0 - 6 表示周一到周天 w,t = calendar.monthrange(2018, 3) print(w) print(t)
1
2
3
4
5
6
7
3 31
1
2
# monthcalendar() 返回一個月每天的矩陣列表 # 格式:calendar.monthcalendar(年,月) # 返回值:二級列表 # 注意:矩陣中沒有天數用0表示 m = calendar.monthcalendar(2018, 3) print(type(m)) print(m)
1
2
3
4
5
6
7
1
2
# prcal: print calendar 直接打印日歷 # calendar.prcal(2018) help(calendar.prcal)
1
2
3
Help on method pryear in module calendar: pryear(theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance Print a year's calendar.
1
2
3
4
# prmonth() 直接打印整個月的日歷 # 格式:calendar.prmonth(年,月) # 返回值:無 calendar.prmonth(2018, 3)
1
2
3
4
March 2018 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
1
2
3
4
5
6
7
# weekend() 獲取周幾 # 格式:calendar.weekday(年,月,日) # 返回值:周幾對應的數字 calendar.weekday(2018, 3, 26)
1
2
3
4
0
1
time模塊
時間戳
- 一個時間表示,根據不同語言,可以是整數或者浮點數 - 是從1970年1月1日0時0分0秒到現在經歷的秒數 - 如果表示的時間是1970年以前或者太遙遠的未來,可能出現異常 - 32為操作系統能夠支持到2038年
1
2
3
4
UTC時間
- UTC時間又稱為世界協調時間,以英國的格林尼治天文所在地區的時間作為參考的時間,也叫做世界標準時間 - 中國時間是 UTC+8 東八區
1
2
夏令時
- 夏令時就是在夏天的時候將時間調快一小時,本意是督促大家早睡早起節省蠟燭!每天變成25個小時,本質沒變還是24小時
1
時間元組
- 一個包含時間內容的普通元組 索引 內容 屬性 值 0 年 tm_year 2015 1 月 tm_mon 1-12 2 日 tm_mday 1-31 3 時 tm_hour 0-23 4 分 tm_min 0-59 5 秒 tm_sec 0-61 60表示閏秒 61保留值 6 周幾 tm_wday 0-6 7 第幾天 tm_yday 1-356 8 夏令時 tm_isdst 0, 1, -1 (表示夏令時)
1
2
3
4
5
6
7
8
9
10
11
12
13
# 需要單獨導入 import time
1
2
# 時間模塊的屬性 # timezone: 當前時區和UTC時間相差的秒數,在沒有夏令時的情況下的間隔, 東八區的是 -28800 # altzone:獲取當前時區與UTC時間相差的秒數,在有夏令時的情況下 # daylight: 測當前是否是夏令時時間狀態,0 表示是 print(time.timezone) print(time.altzone) print(time.daylight)
1
2
3
4
5
6
7
-28800 -32400 0
1
2
3
# 得到時間戳 time.time()
1
2
1559093589.7142274
1
# localtime, 得到當前時間的時間結構 # 可以通過點號操作浮得到相應的屬性元素的內容 t = time.localtime() print(t.tm_hour)
1
2
3
4
9
1
# asctime() 返回元組的正常字符串化之后的時間格式 # 格式:time.asctime(時間元組) # 返回值:字符串 Tue Jun 6 11:11:00 2017 t = time.localtime() tt = time.asctime(t) print(type(tt)) print(tt)
1
2
3
4
5
6
7
1
2
# ctime: 獲取字符串化的當前時間 t = time.ctime() print(type(t)) print(t)
1
2
3
4
1
2
# mktime() 使用時間元組獲取對應的時間戳 # 格式:time.mktime(時間元組) # 返回值:浮點數時間戳 lt = time.localtime() ts = time.mktime(lt) print(type(ts)) print(ts)
1
2
3
4
5
6
7
8
1
2
# clock: 獲取cpu時間,3.0-3.3版本直接使用,3.6調用有問題
1
# sleep:使程序進入睡眠,n秒后繼續 for i in range(10): print(i) time.sleep(1)
1
2
3
4
5
0 1 2 3 4 5 6 7 8 9
1
2
3
4
5
6
7
8
9
10
def p(): time.sleep(2.5) t0 = time.clock() p() t1 = time.clock() print(t1 - t0)
1
2
3
4
5
6
7
8
D:\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead after removing the cwd from sys.path. 2.4999100289999205 D:\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
1
2
3
4
5
6
7
8
# strftime: 將時間轉化為自定義的字符串格式 ''' 格式 含義 備注 %a 本地(locale)簡化星期名稱 %A 本地完整星期名稱 %b 本地簡化月份名稱 %B 本地完整月份名稱 %c 本地相應的日期和時間表示 %d 一個月中的第幾天(01 - 31) %H 一天中的第幾個小時(24小時制,00 - 23) %I 一天中的第幾個小時(12小時制,01 - 12) %j 一天中的第幾天(001 - 366) %m 月份(01 - 12) %M 分鐘數(00 - 59) %p 本地 am 或者 pm的相應符 注1 %S 秒(01 - 61) 注2 %U 一年中的星期數(00 - 53 星期天是一個星期的開始)第一個星期天之前的所有天數都放在 %w 一個星期中的第幾天(0 - 6,0是星期天) 注3 %W 和 %U 基本相同,不同的是 %W 以星期一為一個星期的開始 %x 本地相應日期 %X 本地相應時間 %y 去掉世紀的年份(00 - 99) %Y 完整的年份 %z 用 +HHMM 或 -HHMM 表示距離格林威治的時區偏移(H 代表十進制的小時數,M 代表) %% %號本身 ''' # 把時間表示成: 2018-3-26 21:05 t = time.localtime() ft = time.strftime("%Y-%m-%d %H:%M", t) print(ft)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2019-05-29 09:37
1
datetime模塊
datetime提供日期和時間的運算和表示
import datetime
1
# datetime常見屬性 # datetime.date: 一個理想和的日期,提供year,month,day屬性 dt = datetime.date(2018, 3,26) print(dt) print(dt.day) print(dt.year) print(dt.month) # datetime.time: 提供一個理想和的時間,具有hour, minute, microsec等內容 # datetime.datetime: 提供日期跟時間的組合 # datetime.timedelta: 提供一個時間差,時間長度
1
2
3
4
5
6
7
8
9
10
2018-03-26 26 2018 3
1
2
3
4
# datetime.datetime from datetime import datetime # 常用類方法: # today: # now: # utcnow: # fromtimestamp: 從時間戳中返回本地時間 dt = datetime(2018, 3, 26) print(dt.today()) print(dt.now()) print(dt.fromtimestamp(time.time()))
1
2
3
4
5
6
7
8
9
10
11
12
2019-05-29 09:48:48.809508 2019-05-29 09:48:48.809508 2019-05-29 09:48:48.809508
1
2
3
# datetime.timedelta # 表示一個時間間隔 from datetime import datetime, timedelta t1 = datetime.now() print(t1.strftime("%Y-%m-%d %H:%M:%S")) # td表示一小時的時間長度 td = timedelta(hours=1) # 當前時間加上時間間隔后,把得到的一個小時后的時間格式化輸出 print((t1+td).strftime("%Y-%m-%d %H:%M:%S"))
1
2
3
4
5
6
7
8
9
10
11
2019-05-29 09:53:39 2019-05-29 10:53:39
1
2
# timeit-時間測量工具 # 測量程序運行時間間隔實驗 def p(): time.sleep(3.6) t1 = time.time() p() print(time.time() - t1)
1
2
3
4
5
6
7
8
9
3.600494384765625
1
import timeit # 生成列表兩種方法的比較 # 如果單純比較生成一個列表的時間,可能很難實現 c = ''' sum = [] for i in range(1000): sum.append(i) ''' # 利用timeit調用代碼,執行100000次,查看運行時間 t = timeit.timeit(stmt="[i for i in range(1000)]", number=10000) # 測量代碼c執行100000次運行結果 t2 = timeit.timeit(stmt=c, number=100000) print(t1) print(t2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1559094978.98862 6.657718261000355
1
2
# timeit 可以執行一個函數,來測量一個函數的執行時間 def doIt(): num = 3 for i in range(num): print("Repeat for{0}".format(i)) # 執行函數,重復10次 t = timeit.timeit(stmt=doIt, number=10) print(t)
1
2
3
4
5
6
7
8
9
Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 0.0005245219999778783
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
s = ''' def doIt(num): for i in range(num): print("Repeat for{0}".format(i)) ''' # 執行doIt(num) # setup負責把環境變量準備好 # 實際上相當于給timeit創造了一個小環境 # 在創作的小環境中,代碼執行的順序大致是 # ''' def doIt(num): ... ... num = 3 doIt(num) ''' t = timeit.timeit("doIt(num)", setup=s+"num=3",number=10) print(t)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 Repeat for0 Repeat for1 Repeat for2 0.0016783770001893572
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
datetime.datetime 模塊
提供比較好用的時間而已
類定義
class datetime.datetime(year, month, day[, hour [, minute [, second [, microsecond [, tzinfo]]]]]) # The year, month and day arguments are required. MINYEAR <= year <= MAXYEAR 1 <= month <= 12 1 <= day <= n 0 <= hour < 24 0 <= mintue < 60 0 <= second < 60 0 <= microsecond < 10**
1
2
3
4
5
6
7
8
9
10
11
12
13
類方法
`
datetime.today(): 返回當前本地datetime.隨著 tzion None
datetime.fromtimestamp(time.time()).
datetime.now([tz]):返回當前本地日期和時間,如果可選參數tz為None或沒有詳細說明,
這個方法會像today().
datetime.utcnow(): 返回當前的UTC日期和時間,如果tzifo None,那么與now()類似。
datetime.fromtimestamp(timestamp[, tz]): 根據時間戳返回本地的日期和時間,tz指定時區。
datetime.utcfromtimestamp(timestamp): 根據時間戳返回 UTC datetime.
datetime.fromordinal(ordinal): 根據Gregorian ordinal 返回datetime.
datetime.combine(date, time): 根據date和time返回一個新的datetime.
datetime.strptime(date_string, format): 根據date_string和format返回一個datetime.
實例方法
datetime.date(): 返回相同年月日的date對象.
datetime.time(): 返回相同時分秒微秒的time對象.
datetime.replace(kw): kw in [year, month, day, hour, minute, second,
microsecond, tzindol, 與date類似.類屬性
datetime.min:datetime(MINYEAR,1,1).datetime.max:datetime(MAXYEAR,12,31,23,59,59,999999).
實例屬性(read-only)
datetime.year:1 至 9999 datetime.month:1 至 12 datetime.day:1 至 n datetime.hour:In
range(24).0 至 23 datetime.minute:In range(60).datetime.second:In range(60).
datetime.microsecond:In range(1000000).
`
from datetime import datetime as dt print(dt.now())
1
2
3
2019-05-29 10:45:43.644259
1
os - 操作系統相關
跟操作系統相關,主要是文件操作
與系統相關的操作,主要包含在三個模塊里
os, 操作系統目錄相關
os.path,系統路徑相關操作
shutil,高級文件操作,目錄樹的操作,文件賦值,刪除,移動
路徑:
絕對路徑:總是從根目錄上開始
相對路徑:基本以當前環境為開始的一個相對的地方
os 模塊
import os
1
# getcwd() 獲取當前的工作目錄 # 格式:os.getcwd() # 返回值:當前工作目錄的字符串 # 當前工作目錄就是程序在進行文件相關操作,默認查找文件的目錄 mydir = os.getcwd() print(mydir)
1
2
3
4
5
6
7
d:\Jupyter\nootbook\筆記
1
# chdir() 改變當前的工作目錄 # change directory # 格式: os.chdir(路徑) # 返回值:無 os.chdir('d:\\Jupyter\\nootbook\\筆記') mydir = os.getcwd() print(mydir)
1
2
3
4
5
6
7
8
d:\Jupyter\nootbook\筆記
1
# listdir() 獲取一個目錄中所有子目錄和文件的名稱列表 # 格式:os.listdir(路徑) # 返回值:所有子目錄和文件名稱的列表 # help(os.listdir) ld = os.listdir() print(ld)
1
2
3
4
5
6
7
['.ipynb_checkpoints', 'Jupyter簡單教程.ipynb', 'Jupyter簡單教程.md', 'OOP-1.ipynb', 'OOP-1.md', 'OOP-2.ipynb', 'OOP-2.md', 'OOP-3.ipynb', 'OOP-3.md', 'OOP-4.ipynb', 'OOP-4.md', 'OOP-5.ipynb', 'OOP-5.md', 'str模塊.ipynb', 'str模塊.md', 'Untitled.ipynb', '內置數據結構listsetdicttuple(一).ipynb', '內置數據結構listsetdicttuple(一).md', '內置數據結構listsetdicttuple(三).ipynb', '內置數據結構listsetdicttuple(三).md', '內置數據結構listsetdicttuple(二).ipynb', '內置數據結構listsetdicttuple(二).md', '函數.ipynb', '函數.md', '分支結構.ipynb', '分支結構.md', '變量.ipynb', '變量.md', '變量作用域和列表.ipynb', '變量作用域和列表.md', '常見模塊.ipynb', '異常處理.ipynb', '異常處理.md']
1
# makedirs() 遞歸創建文件夾 # 格式:os.makedirs(遞歸路徑) # 返回值:無 # 遞歸路徑:多個文件夾層層包含的路徑就是遞歸路徑 例如 a/b/c... rst = os.makedirs("ruochen") print(rst)
1
2
3
4
5
6
7
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# system() 運行系統shell命令 # 格式:os.system(系統命令) # 返回值:打開一個shell或者終端界面 # 一般推薦使用subprocess代替 # ls是列出當前文件和文件夾的系統命令 rst = os.system("ls") print(rst) # 在當前目錄下創建一個ruochen.haha 的文件 rst = os.system("touch ruochen.haha") print(rst) mydir = os.getcwd() print(mydir)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1 1 d:\Jupyter\nootbook\筆記
1
2
3
# getenv() 獲取指定的系統環境變量值 # 相應的還有putenv # 格式:os.getenv('環境變量名') # 返回值:指定環境變量名對應的值 rst = os.getenv("PATH") print(rst)
1
2
3
4
5
6
D:\Anaconda3;D:\Anaconda3\Library\mingw-w64\bin;D:\Anaconda3\Library\usr\bin;D:\Anaconda3\Library\bin;D:\Anaconda3\Scripts;D:\Anaconda3;D:\Anaconda3\Library\mingw-w64\bin;D:\Anaconda3\Library\usr\bin;D:\Anaconda3\Library\bin;D:\Anaconda3\Scripts;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;D:\MinGW\bin\;D:\Program Files\Git\Git\cmd;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;D:\python-3.7.0\Scripts\;D:\python-3.7.0\;C:\Users\user\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Java\jdk1.8.0_131\bin;D:\Microsoft VS Code\bin;D:\Anaconda3\Library\bin;D:\Anaconda3;D:\Anaconda3\Scripts;
1
# exit() 退出當前程序 # 格式:exit() # 返回值:無
1
2
3
值部分
os.curdir: curretn dir, 當前目錄
os.pardir: parent dir, 父親目錄
os.sep: 當前系統的路徑分隔符
windows: “”
linux: “/”
os.linesep: 當前系統的路徑換行符號
wndows: “\r\n”
unix,linux,macos: “\n”
os.name: 當前系統名稱
windows: nt
mac,unix,linux: posix
print(os.pardir) print(os.curdir)
1
2
.. .
1
2
print(os.sep) print(os.linesep)
1
2
\
1
# 在路徑相關的操作中,不要手動拼寫地址,因為手動拼寫的路徑可能不具有移植性 path = "d:\\Jupyter" + "\\" + "ruochen" print(path)
1
2
3
d:\Jupyter\ruochen
1
print(os.name)
1
2
nt
1
os.path模塊,跟路徑相關的模塊
import os.path as op
1
# abspath() 將路徑轉化為絕對路徑 # abselute 絕對 # 格式:os.path.abspath('路徑') # 返回值:路徑的絕對路徑形式 # linux中 # . 點號,代表當前目錄 # .. 雙點,代表父目錄 absp = op.abspath(".") print(absp)
1
2
3
4
5
6
7
8
9
10
d:\Jupyter\nootbook\筆記
1
# basename() 獲取路徑中的中文名部分 # 格式:os.path.basename(路徑) # 返回值:文件名字符串 bn = op.basename("d:\Jupyter\nootbook\筆記") print(bn) bn = op.basename("d:\Jupyter\nootbook\筆記") print(bn)
1
2
3
4
5
6
7
8
9
筆記 筆記
1
2
# join() 將多個路徑拼合成一個路徑 # 格式:os.path.join(路徑1,路徑2...) # 返回值:組合之后的新路徑字符串 help(op.join) bd = "d:\\Jupyter\\nootbook" fn = "筆記" p = op.join(bd, fn) print(p)
1
2
3
4
5
6
7
8
9
10
11
Help on function join in module ntpath: join(path, *paths) # Join two (or more) paths. d:\Jupyter\nootbook\筆記
1
2
3
4
5
6
# split() 將路徑切割為文件夾部分和當前文件部分 # 格式:os.path.split(路徑) # 返回值:路徑和文件名組成的元組 t = op.split("d:\\Jupyter\\nootbook\\筆記") print(t) d,p = op.split("d:\\Jupyter\\nootbook\\筆記") print(d, p)
1
2
3
4
5
6
7
8
9
('d:\\Jupyter\\nootbook', '筆記') d:\Jupyter\nootbook 筆記
1
2
# isdir() 檢測是否是目錄 # 格式:os.path.isdir(路徑) # 返回值:布爾值 rst = op.isdir("d:\\Jupyter\\nootbook\\筆記") rst
1
2
3
4
5
6
True
1
# exists() 檢測文件或者目錄是否存在 # 格式:os.path.exists(路徑) # 返回值:布爾值 e = op.exists("d:\\Jupyter\\nootbook\\haha") e
1
2
3
4
5
6
False
1
shutil 模塊
import shutil
1
# copy() 復制文件 # 格式:shutil.copy(來源路徑,目標路徑) # 返回值:返回目標路徑 # 拷貝的同時,可以給文件重名 rst = shutil.copy("d:\\Jupyter\\nootbook\\ruochen.txt", "d:\\Jupyter\\nootbook\\ruo.txt") print(rst)
1
2
3
4
5
6
7
d:\Jupyter\nootbook\ruo.txt
1
# copy2() 復制文件,保留原數據(文件信息) # 格式:shutil.copy2(來源路徑,目標路徑) # 返回值:返回目錄路徑 # 注意:copy和 copy2的唯一區別在于copy2復制文件時盡量保留原數據
1
2
3
4
# copyfile() 將一個文件中的內容復制到另一個文件當中 # 格式:shutil.copyfile('源路徑', '目標路徑') # 返回值:無 rst = shutil.copyfile("d:\\Jupyter\\nootbook\\ruochen.txt", "d:\\Jupyter\\nootbook\\ruo.txt") print(rst)
1
2
3
4
5
6
d:\Jupyter\nootbook\ruo.txt
1
# move() 移動文件/文件夾 # 格式:shutil.move(源路徑,目標路徑) # 返回值:目標路徑 rst = shutil.move("d:\\Jupyter\\nootbook\\ruo.txt", "d:\\Jupyter") print(rst)
1
2
3
4
5
6
--------------------------------------------------------------------------- Error Traceback (most recent call last)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
歸檔和壓縮
歸檔:把多個文件或者文件夾合并到一個文件中
壓縮:用算法把多個文件或者文件夾無損或者有損合并到一個文件當中
# make_archive() 歸檔操作 # 格式:shutil.make_archive("歸檔之后的目錄和文件名","后綴","需要歸檔的文件夾") # 返回值:歸檔之后的地址 # help(shutil.make_archive) rst = shutil.make_archive("d:\\Jupyter\\Jupyter", "zip","d:\\Jupyter\\ruochen") print(rst)
1
2
3
4
5
6
7
d:\Jupyter\Jupyter.zip
1
# unpack_archive() 解包操作 # 格式:shutil.unpack_archive('歸檔文件地址', '解包之后的地址') # 返回值:解包之后的地址
1
2
3
zip - 壓縮包
模塊名稱叫做 zipfile
import zipfile
1
# zipfile.ZipFile(file[, mode[, compression[, allowZip64]]]) # 創建一個ZipFile對象,表示一個Zip文件。參數file表示文件的路徑或類文件對象 zf = zipfile.ZipFile("d:\\Jupyter\\Jupyter.zip") print(zf)
1
2
3
4
5
1
# ZipFile.getinfo(name): # 獲取zip文檔內指定文件的信息。返回一個zipfile.ZipInfo對象,它包括文件的詳細信息。 rst = zf.getinfo("ruochen.txt") print(rst)
1
2
3
4
5
1
# ZipFile.namelist() # 獲取zip文檔內所有文件的名稱列表。 nl = zf.namelist() print(nl)
1
2
3
4
5
['ruo.txt', 'ruochen.txt']
1
# ZipFile.extractall([path[, members[, pwd]]]) # 解壓zip文檔中的所有文件到當前目錄。 rst = zf.extrctall("d:\\Jupyter") print(rst)
1
2
3
4
5
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last)
1
2
3
4
5
6
7
8
9
10
11
12
random
隨機數
所有的隨機模塊都是偽隨機
import random
1
# random() 獲取0-1之間的隨機小數 # 格式:random.random() # 返回值:隨機0-1之間的小數 print(random.random())
1
2
3
4
5
0.8612816713389804
1
# choice() 隨機返回序列中的某個值 # 格式:random.choice(序列) # 返回值:序列中的某個值 l = [str(i)+"haha" for i in range (10)] print(l) rst = random.choice(l) print(rst)
1
2
3
4
5
6
7
8
['0haha', '1haha', '2haha', '3haha', '4haha', '5haha', '6haha', '7haha', '8haha', '9haha'] 1haha
1
2
# shuffle() 隨機打亂列表 # 格式:random.shuffle(列表) # 返回值:打亂順序之后的列表 l1 = [i for i in range(10)] print(l1) random.shuffle(l1) print(l1) # help(random.shuffle)
1
2
3
4
5
6
7
8
9
10
11
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [4, 6, 7, 2, 1, 5, 0, 8, 9, 3]
1
2
# randit(a,b): 返回一個a到b之間的隨機整數,包含a和b print(random.randint(0, 100)) help(random.randint)
1
2
3
4
13 Help on method randint in module random: randint(a, b) method of random.Random instance Return random integer in range [a, b], including both end points.
1
2
3
4
5
Python 數據結構
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。