Python 實現刪除某路徑下檔案及檔案夾

來源:互聯網
上載者:User
下面為大家分享一篇Python 實現刪除某路徑下檔案及檔案夾的執行個體講解,具有很好的參考價值,希望對大家有所協助。一起過來看看吧

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!"

shutil是一個高層次的檔案操作模組。True參數表示ignore_errors(忽略拷貝時候的錯誤)。

類似於進階API,而且主要強大之處在於其對檔案的複製與刪除操作更是比較支援好。

[附] os模組(庫)的使用

有關檔案夾與檔案的尋找,刪除等功能 在 os 模組中實現。

一、取得目前的目錄

#1.1s = os.getcwd()# s 中儲存的是當前的執行目錄(即執行所在的檔案夾)

[注意]

如果是要獲得程式啟動並執行目前的目錄所在位置,那麼可以使用os模組的os.getcwd()函數。

如果是要獲得當前執行的指令碼的所在目錄位置,那麼需要使用sys模組的sys.path[0]變數或者sys.argv[0]來獲得

#1.2import osimport timefolder = time.strftime(r"%Y-%m-%d_%H-%M-%S",time.localtime())os.makedirs(r'%s/%s'%(os.getcwd(),folder))

二、更改目前的目錄

os.chdir( "/root/123")#將目前的目錄設為 "/root/123"#說明: 當指定的目錄不存在時,引發異常。

三、將一個路徑名分解為目錄名和檔案名稱兩部分

fpath , fname = os.path.split( "你要分解的路徑")

例如:

a, b = os.path.split( "/root/123/test.txt" )print aprint b

顯示:

/root/123/test.txt

四、分解檔案名稱的副檔名

fpathandname , fext = os.path.splitext( "你要分解的路徑")

例如:

a, b = os.path.splitext( "/root/123/test.txt" )print aprint b

顯示:

/root/123/test.txt

五、判斷一個路徑( 目錄或檔案)是否存在

b = os.path.exists( "你要判斷的路徑")

傳回值b: True 或 False

六、判斷一個路徑是否檔案

b = os.path.isfile( "你要判斷的路徑")

傳回值b: True 或 False

七、判斷一個路徑是否目錄

b = os.path.isdir( "你要判斷的路徑")

傳回值b: True 或 False

八、擷取某目錄中的檔案及子目錄的列表

L = os.listdir( "你要判斷的路徑")

例如:

L = os.listdir( "/root/123" )print L

顯示 :

[‘test.txt', ‘test.py','python']#這裡面既有檔案也有子目錄

九、建立子目錄

os.makedirs( path )  # path 是"要建立的子目錄"

例如:

os.makedirs("/root/123")

調用有可能失敗,可能的原因是:

(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 檔案。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.