python删除某个目录文件夹及文件的方法:
#!/usr/bin/env python import os import shutil delList = [] delDir = "/home/test" delList = os.listdir(delDir ) for f in delList: filePath = os.path.join( delDir, f ) if os.path.isfile(filePath): os.remove(filePath) print filePath + " was removed!" elif os.path.isdir(filePath): shutil.rmtree(filePath,True) print "Directory: " + filePath +" was removed!"
上述代码主要使用的方法介绍:
os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
listdir()方法语法格式如下:
os.listdir(path)
os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。
remove()方法语法格式如下:
os.remove(path)
shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件。
更多Python知识请关注。
Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务