介绍两种方法
import time
x = time.clock()
#方法1
import string, os, sys
def get_path(dir):
filelist = ”
for root, dirs, files in os.walk(dir):
for name in files:
if name.lower().find(‘.txt’) != -1 or name.lower().find(‘.iso’) != -1:
fp = os.path.join(root, name)
if os.path.isfile(fp) and not os.path.islink(fp):
filelist = filelist + fp + ‘\n’
f = open(r’D:\Share\mspt\filelist-1.txt’,’aw’)
f.write(filelist)
f.close()
dir = r’D:\Share\mspt\MSDN’
for n in range(100):
get_path(dir)
y = time.clock()
f = open(r’D:\Share\mspt\filelist-1.txt’,’aw’)
f.write(‘——————————–\n’)
f.close()
z = time.clock()
#方法2
import os
def ls(arg, dirname, files):
filelist = ”
for x in files:
if os.path.isfile(dirname+’\\’+x) and not os.path.islink(dirname+’\\’+x) and (x.lower().find(‘.txt’)!=-1 or x.lower().find(‘.iso’)!=-1):
filelist = filelist + dirname + ‘\\’ + x + ‘\n’
f = open(r’D:\Share\mspt\filelist-1.txt’,’aw’)
f.write(filelist)
f.close()
for n in range(100):
os.path.walk(r’D:\Share\mspt\MSDN’, ls, None)
zd = time.clock()
print y-x
print zd-z
raw_input()
#3.46223010829
#6.35496271671
#通过测试发现,方法1的速度快于方法2
#但是方法2的更加简单一些