![](/img/trans.png)
[英]Search and replace specific line which starts with specific string in a file
[英]Check if a line in a file starts with a specific string - do some calculations
所以这就是我想做的事情:
我的档案很大。 我想在python中打开它并查看每一行,如果它与某个预定的字符串匹配,我想获取该字符串之后立即出现的数字,将它们全部加起来并得到平均值。
该文件如下所示:
`$` Data
`$` Number of hours: 34
`$` DATA
`$` Number of hours: 56
`$` DATA3
`$` MoreDATA
`$` MOREDATA
`$` Number of hours: 9
我想添加34 + 56 + 9,然后得到平均值。
到目前为止,这就是我所拥有的:
#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"
我不知道应该使用.read()
还是.readlines()
----当我使用readlines时,它不会让我执行rstrip
和lstrip
请通过“小时数”帮助查找该行的所有实例
将文件视为迭代器,以确保仅在实际需要时才读取行,而不是立即将整个文件缓存在内存中:
#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.