在CSV中查找最小值并在Python中打印包含它的每一行

非常感谢您的帮助.我正在尝试编写一个脚本,它将遍历csv文件的文件夹,在第二列中找到最小值并打印包含它的每一行.脚本看起来的csv文件如下所示:

TPN,12010,on this date,25,0.00005047619239909304377497309619
TPN,12011,on this date,23,0.00003797836224092152019127884704
TPN,12012,on this date,78,0.0001130474103447076420049393022
TPN,12020,on this date,27,0.00005671375308512314236202279053
TPN,12021,on this date,60,0.00009856619048244864701475864425

该脚本如下所示:

import csv
import os

folder = '/Users/Documents/Senior/Thesis/Python/TextAnalysis/datedmatchedngrams2/'

identity = []
for filename in os.listdir (folder):
    with open(filename, 'rb') as inf:
        incsv = csv.reader(inf)
        column = 1               
        datatype = int
        data = (datatype(row[column]) for row in incsv)   
        least_value = min(data)
        print least_value
        for row in incsv:
            if least_value in column[1]:
                identity.append(row)
            else:
                print "No match"
        print identity

我得到的错误是:

  File "findfirsttrigram.py", line 12, in <module>
    identity.append("a")
NameError: name 'identity' is not defined

我也试过这样做:

import csv
import os

folder = '/Users/Documents/Senior/Thesis/Python/TextAnalysis/datedmatchedngrams2/'

for filename in os.listdir (folder):
    with open(filename, 'rb') as inf:
        incsv = csv.reader(inf)
        column = 1               
        datatype = int
        data = (datatype(row[column]) for row in incsv)   
        least_value = min(data)
        print least_value
        for row in incsv:
            if least_value in row:
                print row
            else:
                print "No match"

但这也不起作用.它没有给我一个错误,但它也没有打印“不匹配”所以我不知道从哪里开始.请帮忙!!

最佳答案 你可以这样做:

import csv

# for each_file in os.listdir (folder):    
with open(each_file) as f:
    m=min(int(line[1]) for line in csv.reader(f))
    f.seek(0)
    for line in csv.reader(f):
        if int(line[1])==m:
            print line
点赞