Search code examples
pythonif-statementfindall

findall function return all results instead the one specified in in IF clause in python


Here is my code

def ExtractTimeAndFrequency():

for line in ft.split('\r\n'):
    if 'cpu7' in line:
        tm = re.findall(r"([0-2][0-9]:[0-5][0-9]:[0-5][0-9])", line)
        fr= re.findall(r"\d{7}", line)
return fr, tm

file contents are here:

15:23:48 cpu0 1708800
15:23:48 cpu1 1708801
15:23:48 cpu2 1708802
15:23:48 cpu3 1708803
15:23:48 cpu4 1708804
15:23:49 cpu5 1708805
15:23:49 cpu6 2208006
15:23:49 cpu7 2208007
15:23:49 Temp 326

15:23:52 cpu0 1708808
15:23:52 cpu1 1708809
15:23:52 cpu2 1708810
15:23:52 cpu3 1708811
15:23:52 cpu4 1708812
15:23:52 cpu5 1708813
15:23:52 cpu6 2208014
15:23:52 cpu7 2208015
15:23:53 Temp 327

i should be getting only those matches that are for cpu7 but i am getting all the matches from cpu0 to cpu7


Solution

  • You might consider using with open for your file handling (you don't show what you are doing in your code). Then you can extend a list for each additional value of fr and tm. Using extend since each iteration only produces a list with a single value and you probably don't want to over write and just end up with the last value.

    Is something like this what you are looking for (based on your test data)?

    import re
    
    
    def ExtractCpuAndFrequency():
        with open('../testData/so1.txt') as text_file:
            for line in text_file:
                if 'cpu7' in line:
                    tm.extend(re.findall(r"([0-2][0-9]:[0-5][0-9]:[0-5][0-9])", line))
                    fr.extend(re.findall(r"\d{7}", line))
        return fr, tm
    
    
    tm = []
    fr = []
    result_fr, result_tm = ExtractCpuAndFrequency()
    
    print(f'Result fr is {result_fr}')
    print(f'Result tm is {result_tm}')
    

    Results with the two values from the rows with "cpu7":

    Result fr is ['2208007', '2208015']
    Result tm is ['15:23:49', '15:23:52']