首頁 > 後端開發 > Python教學 > python實作刪除檔案或資料夾

python實作刪除檔案或資料夾

巴扎黑
發布: 2017-03-30 14:27:34
原創
1614 人瀏覽過

python 實作刪除檔案或資料夾

         最近自己學習Python 的知識,自己學習抓取網頁的內容知識等,在學習的時候Python刪除資料夾或文件知識的時候,覺得這篇內容不錯,推薦給大家。

實例程式碼,仔細看註解明細:

#-*- coding: UTF-8 -*- 
# 有时候要删除文件夹里文件或文件夹 
# 这个小类用来删除文件或文件夹还是相当有用的 
# 删除文件时有时希看到删除的结果,于是就有了这个Deleter了 
# 下面的一些文件注释用的是Doxygen的样式 
# 用了英文,先就不改回中文吧。 
class Deleter(): 
  def __init__(self, ToPrint=True, Logger=None): 
    self.Logger = Logger 
    self.ToPrint = ToPrint 
    return 
 
  def Log(self, Str): 
    if self.Logger: 
      self.Logger.Log(Str) 
    if self.ToPrint: 
      print Str 
    return 
 
  ## Delete a folder 
  # @param FolderName folder to delete 
  #<br/> 
  #Example: 
  #<pre class="brush:php;toolbar:false"> 
  #  T = Common() 
  #  FolderName = r&#39;Temp&#39; 
  #  T.DeleteFolder(FolderName) 
  #
def DeleteFolder(self, FolderName): '''''delete files and folders''' for Item in os.listdir(FolderName): TempPath = os.path.join(FolderName, Item) if os.path.isfile(TempPath): self.DeleteFile(TempPath) pass elif os.path.isdir(TempPath): self.DeleteFolder(TempPath) pass else: self.Log("Not a file or folder: %s" % (FolderName)) pass pass try: os.rmdir(FolderName) self.Log("Folder deleted: %s" % (FolderName)) except: self.Log("Failed to delete folder: %s" % (FolderName)) pass return ## Delete a file # @param FileName file to delete #
#Example: #
 
  #  T = Common() 
  #  FolderName = r&#39;TempFile.txt&#39; 
  #  T.DeleteFile(FileName) 
  #
def DeleteFile(self, FileName): try: os.remove(FileName) self.Log("File deleted: %s" % (FileName)) except: self.Log("Failed to delete file: %s" % (FileName)) pass return ## Delete a list of folders # @param FolderList a list of folder to delete #
#Example: #
 
  #  T = Common() 
  #  FolderNameList = [r&#39;Temp1&#39;, r&#39;Temp2&#39;] 
  #  T.DeleteFolders(FolderNameList) 
  #
def DeleteFolders(self, FolderNameList): for FolderName in FolderNameList: self.DeleteFolder(FolderName) return ## Delete a list of files # @param FolderList a list of files to delete #
#Example: #
 
  #  T = Common() 
  #  FolderNameList = [r&#39;Temp1.txt&#39;, r&#39;Temp2.txt&#39;] 
  #  T.DeleteFiles(FileNameList) 
  #
def DeleteFiles(self, FileNameList): for FileName in FileNameList: self.DeleteFile(FileName) return Op = Deleter() Op.DeleteFile('a.txt') # Failed to delete file: a.txt
登入後複製

以上是python實作刪除檔案或資料夾的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板