查找一个CSV中所有行的最小值,并将所有行打印到Python中的新文件中

查找一个CSV中所有行的最小值,并将所有行打印到Python中的新文件中,python,csv,min,Python,Csv,Min,我有一个装满csv文件的文件夹,每个文件看起来都像这样: TPN,201203,by the congress,3,0.000001559523908541200542298447130 TPN,201312,by the congress,2,0.000001975728179317089554819047995 TPN,201308,by the congress,2,0.000002130556224313481520620588417 CR,200910,by the congress,

我有一个装满csv文件的文件夹,每个文件看起来都像这样:

TPN,201203,by the congress,3,0.000001559523908541200542298447130
TPN,201312,by the congress,2,0.000001975728179317089554819047995
TPN,201308,by the congress,2,0.000002130556224313481520620588417
CR,200910,by the congress,10,0.000001254229103759238181242376639
CR,200911,by the congress,5,6.974221464170843876612631794E-7
MED,200507,by the congress,2,0.000004113271264069958517659301854
我想要一个脚本,它遍历每个文件并找到该文件中的最小日期值,然后将该文件中包含该日期值的每一行打印到一个新文件中,因此如果两行具有相同的日期值,它应该同时打印这两行。我有这个:

import csv
import os
import codecs 
import unicodecsv

folder = '/Users/xyz/Desktop/TextAnalysis/PointsOfOrigin/trigramsdated/'

c = csv.writer(open("trigrampointsoforigin.csv", "a"))

for file in os.listdir (folder):
    with open(os.path.join(folder, file), mode='rU') as f:
        m=min(int(line[1]) for line in unicodecsv.reader(f, encoding='utf-8', errors='replace'))
        f.seek(0)
        for line in unicodecsv.reader(f):
            if int(line[1])==m:
                print line
                c.writerow(line)

print "All done."
但出于某种奇怪的原因,它只是一致地将每个csv中的最后一行打印到trigramspointsoforign.csv文件中

任何帮助都是非常非常感谢的

第[1]行是否实际打印出日期值?在任何情况下,都可以避免一个内部循环:

for file in os.listdir (folder):
    with open(os.path.join(folder, file), mode='rU') as f:
        minline = [-1,-1] # Some min value
        for linenum, line in enumerate(unicodecsv.reader(f)):
            if int(line[1]) < int(minline[1]):
                # Replace with new minline
                minline = copy.copy(line) 
        print minline
        c.writerow(minline)

您将需要导入副本。

并且每个文件看起来都是这样的:??糟糕!谢谢@AshwiniChaudhary,我已经添加了示例文件。如果它只写最后一行,那么可能c.writerowline没有正确缩进。