Os.walk()与os.path.walk()

来自linux中国网wiki
跳到导航 跳到搜索

os.walk()

函数声明:walk(top,topdown=True,onerror=None)
该函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件列表

一般是路径名 和文件列表比较有用 

os.walk()实例:
evan@evanpc:~/test$ cat  visit.py 
#-*- coding:utf-8 -*-
import os,os.path,sys,shutil
def visitdir(path):
    for root,dirs,files in os.walk(path):
        for filespath in files:
#            print filespath
            print os.path.join(root,filespath)

            
if __name__=="__main__":
    path="/home/evan/test"
    visitdir(path) 


#删除某个文件夹(当然可以通过os.listdir的递归调用删除)
#!/usr/bin/env python
#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"/home/evan/test")


os.path.walk()

evan@evanpc:~/test$ cat visitpa.py 
#-*- coding:utf-8 -*-
#功能其实和上面的代码是一样的
import os.path,sys,shutil
def visitdir(arg,dirname,names):
    for filespath in names:
#        print filespath
#        print dirname
        print os.path.join(dirname,filespath)

            
if __name__=="__main__":
    path="/home/evan/test"
    os.path.walk(path,visitdir,())

os.path.jon

evan@evanpc:~/test$ cat path.join.py
import os
path='/home/evan/test/pytest'
for root, dirs, files in os.walk(path):
    for name in dirs:
        print os.path.join(root,name)
    for file in files:
        pass
#        print os.path.join(root,name,file)
evan@evanpc:~/test$ python path.join.py
/home/evan/test/pytest/RemoteSystemsTempFiles
evan@evanpc:~/test$ ls pytest/
multi.py  mu.py  RemoteSystemsTempFiles



evan@evanpc:~/test$ cat path.join.py
import os
path='/home/evan/test/pytest'
for root, dirs, files in os.walk(path):
    for name in dirs:
        pass
#        print os.path.join(root,name)
    for file in files:
        print os.path.join(root,name,file)
evan@evanpc:~/test$ python path.join.py 
/home/evan/test/pytest/RemoteSystemsTempFiles/multi.py
/home/evan/test/pytest/RemoteSystemsTempFiles/mu.py
/home/evan/test/pytest/RemoteSystemsTempFiles/RemoteSystemsTempFiles/.project

总的 删除目录,shutil.rmtree

evan@evanpc:~/test$ cat walk.py
#-*- coding:utf-8 -*-
#删除指定目录的 test.txt 文件 和svn目录
import os.path,sys,shutil
path ='/home/evan/test/pytest'
for root, dirs, files in os.walk(path):

    for name in files:
        if name=='test.txt':
            os.remove(os.path.join(root,name))

    for name in dirs:
        if name == 'svn':
            print name
            shutil.rmtree(os.path.join(root,name))


参考

Python移动指定后缀名的文件

python-os.walk目录递归

Python之os.walk和os.path.walk