练习os.walk(0遍历目录
#! /usr/bin/env python#coding=utf-8import osimport sys#文件遍历#定义遍历函数,filepath是要遍历的路径,fp是要写入的文件,返回文件listdef dir_walk(filepath): list_file=[] if os.path.exists(filepath): for root,filedirlist,filelist in os.walk(filepath): list_file.append(root) for filename in filelist: #拼接路径,os.path.join;加入list list_file.append(os.path.join(root,filename)) return list_fileif __name__ == '__main__': filepath='E:\\dirty' fp=open('E:\\dirty_walk','w') #这里将文件清空了 fp.truncate() file_list=dir_walk(filepath) fp.seek(0,0) #写入文件 fp.writelines(file_list) fp.close() print 'dir_walk into success'