python刪除某個(gè)目錄文件夾的方法
python刪除某個(gè)目錄文件夾及文件的方法:
#!/usr/bin/env pythonimport osimport shutildelList = []delDir = '/home/test'delList = os.listdir(delDir )for f in delList: filePath = os.path.join( delDir, f ) if os.path.isfile(filePath): os.remove(filePath) print filePath + ' was removed!' elif os.path.isdir(filePath): shutil.rmtree(filePath,True) print 'Directory: ' + filePath +' was removed!'
上述代碼主要使用的方法介紹:
os.listdir() 方法用于返回指定的文件夾包含的文件或文件夾的名字的列表。
listdir()方法語法格式如下:
os.listdir(path)
os.remove() 方法用于刪除指定路徑的文件。如果指定的路徑是一個(gè)目錄,將拋出OSError。
remove()方法語法格式如下:
os.remove(path)
shutil.rmtree() 表示遞歸刪除文件夾下的所有子文件夾和子文件。
內(nèi)容擴(kuò)展:
#!/usr/bin/env pythonimport osimport shutilfilelist=[]rootdir='/home/zoer/aaa'filelist=os.listdir(rootdir)for f in filelist: filepath = os.path.join( rootdir, f ) if os.path.isfile(filepath): os.remove(filepath) print filepath+' removed!' elif os.path.isdir(filepath): shutil.rmtree(filepath,True) print 'dir '+filepath+' removed!'
其中shutil是一個(gè)高層次的文件操作模塊。True參數(shù)表示ignore_errors(忽略拷貝時(shí)候的錯(cuò)誤)。
類似于高級API,而且主要強(qiáng)大之處在于其對文件的復(fù)制與刪除操作更是比較支持好。
比如:
copyfile(src, dst)
是把源文件拷貝到一個(gè)目標(biāo)位置。
以上就是python刪除某個(gè)目錄文件夾的方法的詳細(xì)內(nèi)容,更多關(guān)于python如何刪除某個(gè)目錄文件夾的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟2. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程3. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)4. vue組件庫的在線主題編輯器的實(shí)現(xiàn)思路5. Python安裝并操作redis實(shí)現(xiàn)流程詳解6. 網(wǎng)頁中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測試)7. Python常用擴(kuò)展插件使用教程解析8. html清除浮動(dòng)的6種方法示例9. 用python登錄帶弱圖片驗(yàn)證碼的網(wǎng)站10. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容

網(wǎng)公網(wǎng)安備