在CSV文件中查找特定值

时间:2014-03-31 02:41:57

标签: python

所以我有一个函数可以在csv文件的列中找到最大值。我想打印与最大值在同一行上的值,但是在第13列中。代码使它更清晰:

def bigQuake(inputfilename):

    file = open(inputfilename,"r")
    maxvalue = 0.0
    for line in file:
        value = line.split()
        try:
            p = float(line.split(",")[4])
            maxvalue = max(maxvalue,p)
        except:
            pass
return maxvalue

上面的代码只是找到第4列的最大值,当我替换

时什么不起作用
return maxvalue

print("The largest earthquake was a " + maxvalue + "magnitude earthquake" + value[12])

value [12]试图找到第12列中与第4列的最大值对应的值。注意第12列包含字符串,所以我希望输出看起来像这样:

>>>bigQuake(file.csv)
>>>The largest earthquake was a 50 magnitude earthquake 10km from San Francisco.

1 个答案:

答案 0 :(得分:0)

跟踪第4列中与最大值对应的幅度值。

还可以更好地使用标准库中的csv模块来解析csv文件:

import csv

def bigQuake(inputfilename):
    with open(inputfilename,"r") as input_file:
        reader = csv.reader(input_file)

        maxvalue = 0.0
        magnitude = None
        for line in reader:
            try:
                p = float(line[4])
                if p > maxvalue:
                    maxvalue = p
                    magnitude = line[12]
            except ValueError:
                pass

    print("The largest earthquake was a", maxvalue, "magnitude earthquake", magnitude, ".")

另请注意,在处理文件时应使用with上下文管理器,仅捕获specific to situation exceptions

希望有所帮助。