一个python3遍历目录文件程序
上一篇 /
下一篇 2014-03-27 18:58:38
/ 个人分类:Python3
^2u} k!R5P(]Y)Y|0
一个python3遍历目录文件程序,可以很方便遍历目录下的文件:把以下代码保存为filelist.py,使用方法在cmd下执行filelist.py 'c:\\'即可遍历整个c盘目录下的文件。
]\-L:V SV'Em,S0
import os, sys51Testing软件测试网9ne@~
\
from stat import *
def walktree(top, callback):51Testing软件测试网:qwv&^k"c
'''recursively descend the directory tree rooted at top,
#B7e0h bM\f3Y&d|0 calling the callback function for each regular file'''
for f in os.listdir(top):51Testing软件测试网U C5zcQ+u
pathname = os.path.join(top, f)51Testing软件测试网:?:O]DZa m)xk
R.{3u
try:
0s7E5az
j~!Z2j_;o0 mode = os.stat(pathname).st_mode51Testing软件测试网!A5}n#c zax#S3W*I+Z
except PermissionError:51Testing软件测试网0qf#um'F-tBWlC`
continue
a6t$P(NI p|8a0 else:
uG%WuL{;e0 if S_ISDIR(mode):51Testing软件测试网SQs U`1Ew7T
# It's a directory, recurse into it
c?[#o7x:M0 try:
|\8G!D/n#lf UkT0 walktree(pathname, callback)
/I3en ?$b W0 except PermissionError:51Testing软件测试网IYR b kG_S
continue51Testing软件测试网U$ZDO;H^M4J
elif S_ISREG(mode):51Testing软件测试网+J-S WoK6C/`!Jt z-A
# It's a file, call the callback function51Testing软件测试网 d aO@$^!It9`*aC
callback(pathname)
*DM BZ#@$R0 else:51Testing软件测试网g*Ez1G:m0xo/D
# Unknown file type, print a message
\ ZAg2O!|fv5Y0 print('Skipping %s' % pathname)
def visitfile(file):51Testing软件测试网Z'e*a8y/ku7^
# print('visiting', file)
a+Mn(a*HPi0 with open("filelist.txt",'a') as f:51Testing软件测试网7j9T
e@'B4uOk
try:51Testing软件测试网1{&qx;d2S
f.write(file+"\n")
ZPCF7F^1]N#b0 except Exception:
8XPBqT7D0 pass
!\n g9Pol:J4B.xz0if __name__ == '__main__':
'qeQet!{O8H0 walktree(sys.argv[1], visitfile)51Testing软件测试网ys,v9DvK~3I8bX
收藏
举报
TAG: