详解使用python实现删除文件或文件夹实例代码

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
#
#example:
#
# 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
#
#example:
#
# 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
#
#example:
#
# 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
#
#example:
#
# 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社区 其它相关文章!

Posted in 未分类