您的位置是:网站首页>Python编程Python编程
python如何删除某个目录文件夹?
少儿编程网2021-01-04 13:20:32【Python编程】
人已围观
来源:少儿编程 -用户投稿
简介python删除某个目录文件夹及文件的方法:#!/usr/bin/env pythonimport osimport shutildelList = []delDir = /home/testdelList
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自学网。
来源:php中文网
相关文章:
python面试常见问题有哪些零基础入门Python常见问题分享Python开发岗位求职面试常见问题集高级会计师备考初期!必知的无纸化考学少儿编程有哪些常见问题react面试时会有哪些问题?react面试
支持一下 ( )