查到指定目录下文本所包含的字符

# -*-coding:UTF8-*-
import os
import json

def find_all_text_in_dir_files(dirpath, des_text="CURDIR"):
    dirlist = os.listdir(dirpath)
    textfiletypes = ['txt','py']
    for i in dirlist:
        curpath = dirpath + os.sep + i
        if os.path.isdir(curpath):
            find_all_text_in_dir_files(curpath)
        else:
            if (curpath.split('.')[1] in textfiletypes):
                try:
                    with open(curpath,'r',encoding='UTF8') as f1:
                        text_lines = f1.readlines()
                        for line, text in enumerate(text_lines, 1):
                            if(text.find(des_text) != -1):
                                print("文件路径为:%s" %curpath)
                                print("本文件中找到'%s',在第%d行" %(des_text, line))
                                print(text)
                except Exception as e:
                    print("出错的文件为:%s" % curpath)
                    print(e)

  

猜你喜欢

转载自www.cnblogs.com/yahutiaotiao/p/12650544.html