久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python刪除某個目錄文件夾的方法

瀏覽:4日期:2022-07-24 15:18:21

python刪除某個目錄文件夾及文件的方法:

#!/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() 方法用于刪除指定路徑的文件。如果指定的路徑是一個目錄,將拋出OSError。

remove()方法語法格式如下:

os.remove(path)

shutil.rmtree() 表示遞歸刪除文件夾下的所有子文件夾和子文件。

內容擴展:

#!/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是一個高層次的文件操作模塊。True參數表示ignore_errors(忽略拷貝時候的錯誤)。

類似于高級API,而且主要強大之處在于其對文件的復制與刪除操作更是比較支持好。

比如:

copyfile(src, dst)

是把源文件拷貝到一個目標位置。

以上就是python刪除某個目錄文件夾的方法的詳細內容,更多關于python如何刪除某個目錄文件夾的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 浑源县| 神木县| 中西区| 黄冈市| 霸州市| 馆陶县| 鄂伦春自治旗| 宁国市| 横峰县| 马龙县| 汝城县| 南丰县| 津市市| 定西市| 岑溪市| 湖南省| 乌拉特后旗| 和静县| 汝州市| 庄浪县| 孝义市| 湖南省| 毕节市| 赤城县| 扎赉特旗| 富川| 新晃| 化德县| 山西省| 宜兰市| 三亚市| 桂阳县| 丰县| 屏边| 灵山县| 杂多县| 咸丰县| 泗阳县| 青龙| 内黄县| 且末县|