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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With