新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:PyThon基礎教程:python刪除文件詳細教學
刪除文件是大家經常在做的事情,我們在學習python過程中,知道怎么使用python刪除文件嗎?下面就給大家詳細講解。

python刪除文件的方法:
我們可以采用os.listdir() 方法用于返回指定的文件夾包含的文件或文件夾的名字的列表。
#!/usr/bin/env python import os import shutil delList = [] 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!"
listdir()方法語法格式如下:
os.listdir(path) os.remove() 方法用于刪除指定路徑的文件。如果指定的路徑是一個目錄,將拋出OSError。 remove()方法語法格式如下: os.remove(path) shutil.rmtree() 表示遞歸刪除文件夾下的所有子文件夾和子文件。
內容擴展:
#!/usr/bin/env python import os import shutil filelist=[] 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參數(shù)表示ignore_errors(忽略拷貝時候的錯誤)。
類似于高級API,而且主要強大之處在于其對文件的復制與刪除操作更是比較支持好。
比如:
copyfile(src, dst)
是把源文件拷貝到一個目標位置。
了解以上內容,基本上大家對使用python刪除文件有一定了解,如需了解更多python實用知識,點擊進入PyThon學習網教學中心。
文章名稱:創(chuàng)新互聯(lián)Python教程:PyThon基礎教程:python刪除文件詳細教學
本文路徑:http://www.5511xx.com/article/cdsdhii.html


咨詢
建站咨詢
