Python 3。搜索txt文件时 - -im也可以获取标题以及搜索文本

时间:2016-10-21 12:28:25

标签: regex python-3.x search

关于我正在使用的以下代码的问题 - 工作完美但希望在获得结果时获得更多信息

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

如果我搜索'Bike'

该脚本为我提供了这一行,但也希望包括上面标题中包含/的列表

再次感谢

1 个答案:

答案 0 :(得分:1)

你可以记住最后一个标题:

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="")