Def findstr searches (file_name, str1) :
F=open (file_name)
Length_str=len (str1)
The line=[]
Line_number=0
Location=[]
For each_line in f:
Location_son=[]
Line_number +=1
Length_each_line=len (each_line)
For I in range (length_each_line) : # I control each_line serial number
If each_line [I]==str1 [0] : # each_line detected in the first character of STR
For j in range (1, length_str) : # j control str1 serial number
If each_line [I + j]!=str1 [j] or I + length_str + 1 & gt; Length_each_line:
Break
If j==length_str - 1: # str1 detected
If line_number not in the line:
Line. Append (line_number) # record in str1 the number of rows
Location_son. Append (I + 1)
If location_son:
The location. Append (location_son)
F. lose ()
Length=len (line)
For I in range (length) :
Print (' keyword appears in the first line % d, % s first position '% (line [I], the location [I]))
Def search_file () :
For each_file in OS. Listdir (OS) curdir) :
If OS. Path. Splitext (each_file) [1]=='. TXT ': # detected. TXT file
Path=OS. Getcwd () + OS. Sep + each_file # returns. TXT file path where
Print ("=======================================')
Print (' find keywords in document [% s] [% s] '% (path, str1))
Findstr searches (each_file, str1)
If OS. Path. Isdir (each_file) :
Search_file (#) don't know where is wrong, the recursion depth complains
OS. The chdir (OS. Pardir)
Str1=input (' please enter key words: ')
Search_file ()
CodePudding user response:
Your search_file function recursive directory is a bit complicated, suggested that the directory as the recursive parameter, the code simply
Def search_file (dir) :
For each_file in OS. Listdir (dir) :
If OS. Path. Splitext (each_file) [1]=='. TXT ': # detected. TXT file
Path=dir + OS. Sep + each_file # returns. TXT file's path
Print ("=======================================')
Print (' find keywords in document [% s] [% s] '% (path, str1))
Findstr searches (path, str1)
If OS. Path. Isdir (each_file) :
Search_file (dir + OS + each_file sep) # don't know where is wrong, the recursion depth complains
# OS. Chdir (OS. Pardir)
Str1=input (' please enter key words: ')
Search_file (OS getcwd ())