1.? os模塊中關(guān)于文件目錄函數(shù)使用
1)? os.getcwd() ? 返回當(dāng)前工作目錄
>>> import os
>>> os.getcwd()
'D:\\Pathon軟件\\Pathon'
2)os.chdir(path) ? 改變工作目錄
>>> os.chdir('E:\\')
3)os.listdir(path='.') ? 列舉指定目錄中的文件名('.'表示當(dāng)前目錄履怯,'..'表示上級目錄)
>>> os.listdir('C:\\')
['$RECYCLE.BIN', 'Config.Msi', 'Documents and Settings', 'hiberfil.sys', 'Intel', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'Recycler', 'swapfile.sys', 'System Volume Information', 'Users', 'Windows']
4)os.mkdir(path)? 創(chuàng)建單層目錄,若該目錄已存在拋出異常
>>> os.mkdir('d:\\A Plan\\B Plan')
5)os.makedirs(path)? 遞歸創(chuàng)建多層目錄裆泳,若該目錄已存在拋出異常(注意:'E:\\a\\b'和'E:\\a\\c'并不會沖突)
>>> os.makedirs('d:\\A Plan\\B Plan')
6)os.remove(path) ? 刪除文件
os.removedirs('d:\\A Plan\\B Plan')
7)os.rmdir(path) ? 刪除單層目錄叹洲,若該目錄非空擇拋出異常
>>> os.rmdir('d:\\A Plan\\B Plan')
8)os.removedirs(path)? 遞歸刪除目錄,從子目錄到父目錄逐層嘗試刪除工禾,遇到目錄非空則拋出異常
>>> os.removedirs('d:\\A Plan\\B Plan')
9)os.rename(old, new) ? 將文件old重命名為new
2.? os.path模塊中關(guān)于常用路徑的函數(shù)使用
1)os.path.basename(path) ? 去掉目錄路徑运提,單獨(dú)返回文件名
>>> os.path.basename('D:\2010\第11章\\工資管理系統(tǒng).xlsm')
'工資管理系統(tǒng).xlsm'
2) ?os.path.dirname(path) ? 去掉文件名,單獨(dú)返回目錄路徑
>>> os.path.dirname('D:\2010\第11章\\工資管理系統(tǒng).xlsm')
'D:\x810\\第11章'
3)os.path.join(path1 [,path2] [,... ]) ?? 將path1闻葵、path2各部分合成一個路徑名
>>> os.path.join('d:\\','A', 'B','C')
'd:\\A\\B\\C'
4)os.path.split(path) ?? 分割文件名和路徑民泵,返回(file_path, file_name)元組。如果完全使用目錄槽畔,它也會將最后一個目錄作為文件名分離栈妆,且不會判斷文件或者目錄是否存在。
>>> os.path.split('D:\2010\第11章\\工資管理系統(tǒng).xlsm')
('D:\x810\\第11章', '工資管理系統(tǒng).xlsm')
5)os.path.splitext(path) ? 分離文件名和擴(kuò)展名厢钧,返回(file_name, file_extension)元組鳞尔。
>>> os.path.splitext('D:\2010\第11章\\工資管理系統(tǒng).xlsm')
('D:\x810\\第11章\\工資管理系統(tǒng)', '.xlsm')
6)os.path.getsize(file) ? 返回指定文件的尺寸,單位是字節(jié)
>>> file = r'd://2010/第11章/工資管理系統(tǒng).xlsm'
>>> os.path.getsize(file)
137604
7)os.path.getatime() / getctime() / getmtime() ? 返回指定文件的當(dāng)前時間/創(chuàng)建時間/修改時間(ps:活得浮點(diǎn)型秒數(shù)早直,可用time模塊的gtime()或者localtime()函數(shù)換算)
>>> import time
>>> time.gmtime(os.path.getatime('D:\\demo.txt'))
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=20, tm_hour=13, tm_min=17, tm_sec=7, tm_wday=5, tm_yday=201, tm_isdst=0)
>>> time.localtime(os.path.getatime('D:\\demo.txt'))
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=20, tm_hour=21, tm_min=17, tm_sec=7, tm_wday=5, tm_yday=201, tm_isdst=0)
>>> time.localtime(os.path.getmtime('D:\\demo.txt'))
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=20, tm_hour=21, tm_min=22, tm_sec=31, tm_wday=5, tm_yday=201, tm_isdst=0)
>>> time.localtime(os.path.getctime('D:\\demo.txt'))
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=20, tm_hour=21, tm_min=17, tm_sec=7, tm_wday=5, tm_yday=201, tm_isdst=0)