极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

python如何删除某个目录文件夹?

极客小将2021-01-04-
简介python删除某个目录文件夹及文件的方法:#!/usr/bin/env pythonimport osimport shutildelList = []delDir = /home/testdelList
版权所有:https://wWw.pxcodeS.com

LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

python删除某个目录文件夹及文件的方法:LbI少儿编程网-Scratch_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!"

上述代码主要使用的方法介绍:
LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

listdir()方法语法格式如下:LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

os.listdir(path)

os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

remove()方法语法格式如下:LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

os.remove(path)

shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件。LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

更多Python知识请关注Python自学网。LbI少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

网友点评

共有5条评论来说两句吧...

在线客服