函数声明:os.walk(top,topdown=True,οnerrοr=None)
(1)参数top表示需要遍历的顶级目录的路径。
(2)参数topdown的默认值是“True”表示首先返回顶级目录下的文件,然后再遍历子目录中的文件。当topdown的值为"False"时,表示先遍历子目录中的文件,然后再返回顶级目录下的文件。
(3)参数onerror默认值为"None",表示忽略文件遍历时的错误。如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历。
返回值:函数返回一个元组,含有三个元素tuple(dirpath, dirnames, filenames)。这三个元素分别是:每次遍历的路径名dirpath、路径下子目录列表dirnames、目录下文件列表filenames。
dirpath 是string,代表目录的路径;dirnames 是list,包含dirpath 下所有子目录名;filenames是list,包含非目录文件名。
这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name)。
通过for循环自动完成递归枚举。
例如:F:\aaa 目录是这样的文件目录结构
F:\aaa
|--------1.txt
|--------2.txt
|--------3.txt
|--------4
|-------5.txt
|-------6.txt
|-------7.txt
# use UTF-8
# os.walk()的使用
import os
# 枚举dirPath目录下的所有文件
def main():
fileDir = "F:" + os.sep + "aaa" # 查找F:\aaa 目录下
for root, dirs, files in os.walk(fileDir):
print(root)
print(dirs)
print(files)
os.system("pause")
if __name__ == '__main__':
main()
# 输出
# F:\aaa
# ['4']
# ['1.txt', '2.txt', '3.txt']
# F:\aaa\4
# []
# ['5.txt', '6.txt', '7.txt']
也可以这样:
# use UTF-8
# os.walk()的使用
import os
# 枚举dirPath目录下的所有文件
def main():
fileDir = "F:" + os.sep + "aaa" # 查找F:\aaa 目录下
for a in os.walk(fileDir):
print(a[0])
print(a[1])
print(a[2])
os.system("pause")
if __name__ == '__main__':
main()
# 输出
# F:\aaa
# ['4']
# ['1.txt', '2.txt', '3.txt']
# F:\aaa\4
# []
# ['5.txt', '6.txt', '7.txt']
通过for循环即可完成目录的递归。
还可以这样:
# use UTF-8
# os.walk()的使用
import os
# 枚举dirPath目录下的所有文件
def main():
fileDir = "F:" + os.sep + "aaa" # 查找F:\aaa 目录下
for root, dirs, files in os.walk(fileDir):
for dir in dirs:
print(os.path.join(root, dir))
for file in files:
print(os.path.join(root, file))
os.system("pause")
if __name__ == '__main__':
main()
# 输出
# F:\aaa\4
# F:\aaa\1.txt
# F:\aaa\2.txt
# F:\aaa\3.txt
# F:\aaa\4\5.txt
# F:\aaa\4\6.txt
# F:\aaa\4\7.txt
删除某个文件夹(当然可以通过os.listdir的递归调用删除):
#coding=utf-8
import os
def Remove_dir(top_dir):
if os.path.exists(top_dir)==False:
print "not exists"
return
if os.path.isdir(top_dir)==False:
print "not a dir"
return
for dir_path,subpaths,files in os.walk(top_dir,False):
for file in files:
file_path=os.path.join(dir_path,file)
print "delete file:%s" %file_path
os.remove(file_path)
print "delete dir:%s" %dir_path
os.rmdir(dir_path)
#调用
Remove_dir(r"C:\Users\Administrator\Desktop\zrbuN7zRuc")