Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a line in a file starts with a specific string - do some calculations

Tags:

python

So this is what im trying to do:

I have a huge file. I want to open it in python and look at each line, if it matches a certain predetermined string I want to get the number that comes immediately after that string, add them all up and get the average.

the file looks like this:

`$` Data
`$` Number of hours: 34
`$` DATA
`$` Number of hours: 56
`$` DATA3
`$` MoreDATA
`$` MOREDATA
`$` Number of hours: 9

I want to add 34 + 56 + 9 and then get the average.

So far this is what I have:


#fname = raw_input("Enter file name: ")
fh = open("data.txt")


fhread = fh.readlines()
#fhstrip = fhread.rstrip()
#fhstripz = fhstrip.lstrip()

findz = "Number of hours:"

for line in fhread:
    if line.startswith(findz)
    print line
    #print saved
    #spose = line.find('', atpos)


fh.close()    

print "Done"    

I dont know if I should use .read() or .readlines() ----When I use readlines it does not let me do rstrip and lstrip

Please help find all instances of the line with "Number of hours"

like image 230
Jimmy Avatar asked Mar 16 '23 08:03

Jimmy


1 Answers

Treat the file as an iterator, which ensures that lines will only be read as they are actually needed, rather than caching the entire file in memory at once:

#fname = raw_input("Enter file name: ")
with open("data.txt") as fh:
    for line in fh:
        if line.startswith("Number of hours:"):
            print line
like image 90
chepner Avatar answered Apr 27 '23 00:04

chepner