python 刪除非空目錄

raysuen發表於2018-07-09

點選(此處)摺疊或開啟

  1. #!/usr/bin/env python3
  2. # _*_coding:utf-8_*_
  3. # Auth by raysuen

  4. import os,sys

  5. def ForceRMDir(DirName):
  6.     ret = 0
  7.     try:
  8.         os.rmdir(os.path.abspath(DirName))
  9.     except FileNotFoundError as e:
  10.         print(e)
  11.         ret = 1
  12.     except OSError as e:
  13.         for i in os.listdir(os.path.abspath(DirName)):
  14.             if os.path.isfile("%s/%s"%(os.path.abspath(DirName),i)):
  15.                 os.remove("%s/%s"%(os.path.abspath(DirName),i))
  16.             else:
  17.                 ForceRMDir("%s/%s"%(os.path.abspath(DirName),i))
  18.     except Exception as e:
  19.         print(e)
  20.         return 2
  21.     finally:
  22.         if ret == 0:
  23.             os.rmdir(os.path.abspath(DirName))
  24.         return ret

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28572479/viewspace-2157561/,如需轉載,請註明出處,否則將追究法律責任。

相關文章