python遍历查找指定路径下文件 或指定后缀名的文件

import os
# 递归遍历指定的目录
# level -- 递归的层数,用这个参数来控制打印的缩进
# path  == 遍历起始绝对路径
def listyoudir(level, path):
    for i in os.listdir(path):
        print '  '*(level+1) + i
        if os.path.isdir(path + '\\' + i):
            listyoudir(level+1, path + '\\' + i)

#测试代码
rootpath = os.path.abspath('.')
print rootpath
listyoudir(0, rootpath)

#第二种方法:使用os.walk:

def Test1(rootDir):
    list_dirs = os.walk(rootDir)
    for root, dirs, files in list_dirs:
        for d in dirs:
            print os.path.join(root, d)
        for f in files:
            print os.path.join(root, f)

Test1('E:\\')

#第三种方法:
#python查找遍历指定文件路径下指定后缀名的文件
for dirpath, dirnames, filenames in os.walk(startdir):
        for filename in filenames:
            if os.path.splitext(filename)[1] == '.txt':
               filepath = os.path.join(dirpath, filename)
               #print("file:" + filepath)
               input_file = open(filepath)
               text = input_file.read()
               input_file.close()

               output_file = open( filepath, 'w')
               output_file.write(text)
               output_file.close()

您可以选择一种方式赞助本站