olearydc
olearydc

Reputation: 13

Python 3 . When searching txt file - -aim to also get title as well as searched text

Just a question on thefollowing bit of code I am using -- Works perfect but hoping to get more information when getting results

search_path = ('location of myfile.txt')
file_type = ('myfile.txt')
search_str = input("Enter the search string : ").strip()


if not (search_path.endswith("/") or search_path.endswith("\\") ): 
        search_path = search_path + "/"


if not os.path.exists(search_path):
        search_path ="."


for fname in os.listdir(path=search_path):

   # Apply file type filter   
   if fname.endswith(file_type):

    # Open file for reading
    fo = open(search_path + fname)

    # Read the first line from the file
    line = fo.readline()

    # Initialize counter for line number
    line_no = 1


                                                            # Search for string with lower case
            index = line.find(search_lower)
            if ( index != -1) :
                print(fname, "[", line_no, ",", index, "] ", line, sep="")




            # Read next line
            line = fo.readline()  

            # Increment line counter
            line_no += 1
    # Close the files
    fo.close()

================================

myfile.txt



/This is in the first one- - -1 : Color
Name             Value
---------------  ---------------------------------------------------------------------------------------
Blue             Car
Green            Drive
Red      Bike


/This is in the 2nd one- - -2 : Gears
Name             Value
---------------  ---------------------------------------------------------------------------------------
Auto             Car
Man      Drive
None         Bike

If I do a search for 'Bike'

The script gives me the line but would also like in include the title above which contains the / in its listing

Thanks again

Dan

Upvotes: 1

Views: 53

Answers (1)

Stanislav Ivanov
Stanislav Ivanov

Reputation: 1974

You can memorise last title:

last_head = ""

... # for all line in file:

if len(line) > 0 and line.startswith('/'):
    last_head = line.strip()[1:]

if index != -1 :
    print(fname, last_head, "[", line_no, ",", index, "] ", line, sep="")

Upvotes: 1

Related Questions