小甲魚の第30課の授業の後で第4題

10042 ワード

小甲魚の第30課の授業の後で第4題
指定したディレクトリと検索する文字を入力し、txtのいくつかの行のいくつかの位置を検索します.組み込み関数はありません.
import os

def search_ext(start_file,key) :
    os.chdir(start_file)

    i=0
    
    k=0

    list=[]

    list1=set()
    
    try:
        for each_file in os.listdir(os.curdir) :#                 ,    
            ext = os.path.splitext(each_file)[1]#            ,         (     :    2   ‘’。                 
            if ext=='.txt' :
                f=open(os.getcwd() + os.sep + each_file) #     txt      

                for line in f.readlines():
                    i+=1
                    if key in line:

                        path1='   【'+os.getcwd() + os.sep + each_file+'】      【'+key +'】
'
# list1.add(path1) k = line.find(key) pos=[] # while k != -1: # key pos[] pos.append(k+1) k=line.find(key,k+1) # key ( -1) for j in pos: path=' 【 ' + str(i) + ' 】 【' + str(j) + ' 】
'
# list.append(path) pos=[] # for line in f.readlines() , for c in list1: # key print(c) for n in list: # # key , key print(n) list=[] # list1.clear() f.close() if os.path.isdir(each_file):# #os.chdir(os.getcwd()+os.sep+each_file) # ********* start_file=os.getcwd()+os.sep+each_file search_ext(start_file,key) # os.chdir(os.pardir) # 。os.pardir ( ) except: # os.chdir(os.pardir) start_file=input('
:'
) key = input('
:'
) search_ext(start_file,key)