一个python3遍历目录文件程序

上一篇 / 下一篇  2014-03-27 18:58:38 / 个人分类:Python3


f G$g|-VP%D0
一个python3遍历目录文件程序,可以很方便遍历目录下的文件:把以下代码保存为filelist.py,使用方法在cmd下执行filelist.py 'c:\\'即可遍历整个c盘目录下的文件。

OjFG:Gf^hq0
import os, sys
Y j,Y`IC;S5]7q[:PT0from stat import *
def walktree(top, callback):
AI8n qa3{*l6f0    '''recursively descend the directory tree rooted at top,
l \)`S Is_[^-m^0       calling the callback function for each regular file'''
    for f in os.listdir(top):51Testing软件测试网@d1`$gm}*k^
        pathname = os.path.join(top, f)
O v%_ ?#z^0        try:51Testing软件测试网9Y(j+~RCI
            mode = os.stat(pathname).st_mode51Testing软件测试网h R&E3TKzzZ
        except PermissionError:51Testing软件测试网 J V.Qwh
            continue51Testing软件测试网f_yHw:[x
        else:51Testing软件测试网&~l1j3D4_u&Qe
            if S_ISDIR(mode):
{t yG;\QMG+Y0                # It's a directory, recurse into it51Testing软件测试网$H.a~D6\4px3c
                try:51Testing软件测试网y`2w(s)M k4{I
                    walktree(pathname, callback)51Testing软件测试网M!\P)lf XT9f5R#U
                except PermissionError:51Testing软件测试网*iG8iyQ9tH4B
                    continue
)KoJ,hp0h)D7Pt%Z0            elif S_ISREG(mode):
@+x['sy:n0                    # It's a file, call the callback function
~_A*} VR$J;B Rm0                    callback(pathname)
_?0?&^#TGT0            else:
&V"[l al!YE0                # Unknown file type, print a message51Testing软件测试网x t,M*G _U n:E
                print('Skipping %s' % pathname)
def visitfile(file):51Testing软件测试网 Xd#Q;Rk@&~.Q
     # print('visiting', file)
I@8d@EPs*O0      with open("filelist.txt",'a') as f:51Testing软件测试网\fj/e#Y!P\o7It[
          try:51Testing软件测试网fTr jrH nv1f}
              f.write(file+"\n")51Testing软件测试网$m3Z+Y6Vru3i
          except Exception:51Testing软件测试网WcR8v`*E+M
              pass
51Testing软件测试网ou,U8fJ+A
if __name__ == '__main__':
(eI.Z"rCr4c0    walktree(sys.argv[1], visitfile)
,T m%WZ s%M-e[0

TAG:

 

评分:0

我来说两句

Open Toolbar