[英]Check if a line in a file starts with a specific string - do some calculations
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.
我想在python中打开它并查看每一行,如果它与某个预定的字符串匹配,我想获取该字符串之后立即出现的数字,将它们全部加起来并得到平均值。
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. 我想添加34 + 56 + 9,然后得到平均值。
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
我不知道应该使用
.read()
还是.readlines()
----当我使用readlines时,它不会让我执行rstrip
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.