This is a tricky question and I've read a lot of posts about it, but I haven't been able to make it work.
I have a big file. I need to read it line by line, and once I reach a line of the form "Total is: (any decimal number)"
, take this string and to save the number in a variable. If the number is bigger than 40.0, then I need to find the fourth line above the Total
line (for example, if the Total
line was line 39, this line would be line 35). This line will be in the format "(number).(space)(substring)"
. Finally, I need to parse this substring out and do further processing on it.
This is an example of what an input file might look like:
many lines that we don't care about
many lines that we don't care about
...
1. Hi45
People: bla bla bla bla bla bla
whitespace
bla bla bla bla bla
Total is: (*here there will be a decimal number*)
bla bla
white space
...
more lines we don't care about
and then more lines and then
again we get
2. How144
People: bla bla bla bla bla bla
whitespace
bla bla bla bla bla
Total is: (*here there will be a decimal number*)
bla bla
white space
I have tried many things, including using the re.search()
method to capture what I need from each line I need to focus on.
Here is my code which I modified from another stackoverflow Q & A:
import re
import linecache
number = ""
higher_line = ""
found_line = ""
with open("filename_with_many_lines.txt") as aFile:
for num, line in enumerate(aFile, 1):
searchObj = re.search(r'(\bTotal\b)(\s)(\w+)(\:)(\s)(\d+.\d+)', line)
if searchObj:
print "this is on line", line
print "this is the line number:", num
var1 = searchObj.group(6)
print var1
if float(var1) > 40.0:
number = num
higher_line = number - 4
print number
print higher_line
found_line = linecache.getline("filename_with_many_lines.txt", higher_line)
print "found the", found_line
The expected output would be:
this is on line Total is: 45.5
this is the line number: 14857
14857
14853
found the 1. Hi145
this is on line Total is: 62.1
this is the line number: 14985
14985
14981
found the 2.How144
close()
on a file is not necessary if it was opened in the header of awith
statement.