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'Temp' # 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 #
# T = Common() # FolderName = r'TempFile.txt' # 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 #
# T = Common() # FolderNameList = [r'Temp1', r'Temp2'] # 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 #
# T = Common() # FolderNameList = [r'Temp1.txt', r'Temp2.txt'] # 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!