python如何删除某个目录文件夹?
发布时间:2026-01-22 21:41:46

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() 该方法用于删除指定路径的文件。若指定路径为目录,则抛出OSEror。
remove方法语法格式如下:
os.remove(path)
shutil.rmtree() 所有子文件夹和子文件都表示递归删除文件夹。
请关注Python自学网了解更多Python知识。
下一篇 返回列表
