python删除某个目录文件夹的方法
python删除某个目录文件夹及文件的方法:
#!/usr/bin/envpython importos importshutil delList=[] delDir="/home/test" delList=os.listdir(delDir) forfindelList: filePath=os.path.join(delDir,f) ifos.path.isfile(filePath): os.remove(filePath) printfilePath+"wasremoved!" elifos.path.isdir(filePath): shutil.rmtree(filePath,True) print"Directory:"+filePath+"wasremoved!"
上述代码主要使用的方法介绍:
os.listdir()方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
listdir()方法语法格式如下:
os.listdir(path)
os.remove()方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。
remove()方法语法格式如下:
os.remove(path)
shutil.rmtree()表示递归删除文件夹下的所有子文件夹和子文件。
内容扩展:
#!/usr/bin/envpython
importos
importshutil
filelist=[]
rootdir="/home/zoer/aaa"
filelist=os.listdir(rootdir)
forfinfilelist:
filepath=os.path.join(rootdir,f)
ifos.path.isfile(filepath):
os.remove(filepath)
printfilepath+"removed!"
elifos.path.isdir(filepath):
shutil.rmtree(filepath,True)
print"dir"+filepath+"removed!"
其中shutil是一个高层次的文件操作模块。True参数表示ignore_errors(忽略拷贝时候的错误)。
类似于高级API,而且主要强大之处在于其对文件的复制与删除操作更是比较支持好。
比如:
copyfile(src,dst)
是把源文件拷贝到一个目标位置。
以上就是python删除某个目录文件夹的方法的详细内容,更多关于python如何删除某个目录文件夹的资料请关注毛票票其它相关文章!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下