发布时间:2022-06-01 09:38:20 人气:549 作者:多测师
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如何删除某个目录文件夹?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/