简体   繁体   English

检查文件中的行是否以特定字符串开头-进行一些计算

[英]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时,它不会让我执行rstriplstrip

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.

相关问题 搜索并替换以文件中的特定字符串开头的特定行 - Search and replace specific line which starts with specific string in a file 检查以特定字符串开头的列表 - Check a list that starts with a specific string 获取以文件中的特定字符串开头的行,并将其与python中的其他字符串进行比较 - Getting a line that starts with a specific string in a file and compare it with another strings in python 如何检查文件的每一行是否以空格开头? - How to check if each line of a file starts with a whitespace? 逐行读取文件,并获得以某个单词开头的行? - Read a file line by line,and get the line that starts with some word? Pandas中,如何对特定的连续列做一些算术计算 - In Pandas, how to do some arithmetic calculations for specific consecutive columns 如何检查文本文件中的行是否等于特定字符串? - How to check if line in text file equals to a specific string? 如何检查文本文件中每一行末尾的特定字符 - How do check for a specific character at the end of each line in a text file 检查行是否以列表中的字符串开头的首选方法? - Preferred way to check if a line starts with a string from list? 如何从巨大的文本文件(> 16GB)中提取特定行,其中每行以另一个输入文件中指定的字符串开头? - How to extract specific lines from a huge text file (>16GB) where each line starts with a string specified in another input file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM