有關檔案夾與檔案的查找,删除等功能 在 os 子產品中實作。使用時需先導入這個子產品,
導入的方法是:
import os
一、取得目前目錄
s = os.getcwd()
# s 中儲存的是目前目錄(即檔案夾)
比如運作abc.py,那麼輸入該指令就會傳回abc所在的檔案夾位置。
舉個簡單例子,我們将abc.py放入a檔案夾。并且希望不管将a檔案夾放在硬碟的哪個位置,都可以在a檔案夾内生成一個新檔案夾。且檔案夾的名字根據時間自動生成。
import time
folder = time.strftime(r"%y-%m-%d_%h-%m-%s",time.localtime())
os.makedirs(r'%s/%s'%(os.getcwd(),folder))
二、更改目前目錄
os.chdir( "c:\\123")
#将目前目錄設為 "c:\123", 相當于doc指令的 cd c:\123
#說明: 當指定的目錄不存在時,引發異常。
異常類型:windowserror
linux下沒去試,不知是哪種
三 将一個路徑名分解為目錄名和檔案名兩部分
fpath , fname = os.path.split( "你要分解的路徑")
例如:
a, b = os.path.split(
"c:\\123\\456\\test.txt" )
print a
print b
顯示:
c:\123\456
test.txt
四 分解檔案名的擴充名
fpathandname , fext = os.path.splitext( "你要分解的路徑")
a, b = os.path.splitext(
c:\123\456\test
.txt
五、判斷一個路徑( 目錄或檔案)是否存在
b = os.path.exists( "你要判斷的路徑")
傳回值b: true 或 false
六、判斷一個路徑是否檔案
b = os.path.isfile( "你要判斷的路徑")
七、判斷一個路徑是否目錄
b = os.path.isdir( "你要判斷的路徑")
八、擷取某目錄中的檔案及子目錄的清單
l = os.listdir( "你要判斷的路徑")
l = os.listdir(
"c:/" )
print l
顯示 :
['1.avi', '1.jpg', '1.txt', 'config.sys', 'inetpub', 'io.sys', 'kcbjgdjc', 'kcbjgdyb', 'kf_gssy_jc', 'msdos.sys', 'msocache', 'ntdetect.com', 'ntldr',
'pagefile.sys', 'pdoxusrs.net', 'program files', 'python24', 'python31', 'qqvideo.cache', 'recycler', 'system volume information', 'tddownload', 'test.txt', 'windows']
這裡面既有檔案也有子目錄
1 擷取某指定目錄下的所有子目錄的清單
def getdirlist( p ):
p = str( p )
if p=="":
return [ ]
p = p.replace( "/","\\")
if p[ -1] != "\\":
p = p+"\\"
a = os.listdir( p )
b = [ x for x in a if os.path.isdir(
p + x ) ]
return b
print getdirlist( "c:\\" )
結果:
['documents and settings', 'downloads', 'htdzh', 'kcbjgdjc', 'kcbjgdyb', 'kf_gssy_jc', 'msocache', 'program files', 'python24', 'python31', 'qqvideo.cache',
'recycler', 'system volume information', 'tddownload', 'windows']
2 擷取某指定目錄下的所有檔案的清單
def getfilelist( p ):
b = [ x for x in a if os.path.isfile(
print getfilelist( "c:\\" )
['1.avi', '1.jpg', '1.txt', '123.txt', '12345.txt', '2.avi', 'a.py', 'autoexec.bat', 'boot.ini', 'bootfont.bin', 'config.sys', 'io.sys', 'msdos.sys',
'ntdetect.com', 'ntldr', 'pagefile.sys', 'pdoxusrs.net', 'test.txt']
九、建立子目錄
os.makedirs( path ) # path
是"要建立的子目錄"
例如:
os.makedirs( "c:\\123\\456\\789")
調用有可能失敗,可能的原因是:
(1) path 已存在時(不管是檔案還是檔案夾)
(2) 驅動器不存在
(3) 磁盤已滿
(4)磁盤是隻讀的或沒有寫權限
十、删除子目錄
os.rmdir( path ) # path: "要删除的子目錄"
産生異常的可能原因:
(1) path 不存在
(2) path 子目錄中有檔案或下級子目錄
(3) 沒有操作權限或隻讀
測試該函數時,請自已先建立子目錄。
十一、删除檔案
os.remove( filename ) # filename: "要删除的檔案名"
(1) filename 不存在
(2) 對filename檔案, 沒有操作權限或隻讀。
十二、檔案改名
os.name( oldfilename, newfilename)
産生異常的原因:
(1) oldfilename 舊檔案名不存在
(2) newfilename 新檔案已經存在時,此時,您需要先删除 newfilename 檔案。
---我是低調的不顯眼的簡潔的不會被敵人發現的分割線---