2012-10-15 67 views
0

我想從csv文件中找到最小值和最大值,並將其輸出到文本文件中,當前我的代碼將所有數據輸出到輸出文件中,並且我不確定如何從多個列中獲取數據並對其進行相應排序。從文件中排序列表,在另一個文件中輸出

任何指導,將不勝感激,因爲我沒有對如何算出這個

read_file = open("riskfactors.csv", 'r') 

def create_file(): 

    read_file = open("riskfactors.csv", 'r') 
    write_file = open("best_and_worst.txt", "w") 

    for line_str in read_file: 
     read_file.readline() 
     print (line_str,file=write_file) 

    write_file.close() 
    read_file.close() 
+7

看看了'csv'模塊 - 這是建立這樣做:) – RocketDonkey

+0

當你說最小和最大,你的意思是每個列的最小和最大的條目,或在某些特定列的最小值和最大值的行?或者是其他東西。 – Dougal

回答

2

假設你的文件只包含由分號分隔的數字標準.csv文件帶了好頭:

1;5;7;6; 
3;8;1;1; 

然後,最簡單的方法是使用str.split()命令,然後將類型轉換爲int。 你可以存儲所有值列表(或更快:集),然後得到最大:

valuelist=[] 
for line_str in read_file: 
    for cell in line_str.split(";"): 
     valuelist.append(int(cell)) 
print(max(valuelist)) 
print(min(valuelist)) 

警告:如果您的文件包含非條目數量,你不得不將它們過濾出來。 .csv文件也可以有不同的分隔符。現在

+0

我不會用分號分隔標準,因爲畢竟csv代表*逗號*分隔的值。 – Dougal

+0

看起來不錯,但是我的逗號也是,謝謝! –

1
import sys, csv 

def cmp_risks(x, y): 
    # This assumes risk factors are prioritised by key columns 1, 3 
    # and that column 1 is numeric while column 3 is textual 
    return cmp(int(x[0]), int(y[0])) or cmp(x[2], y[2]) 

l = sorted(csv.reader(sys.stdin), cmp_risks)) 

# Write out the first and last rows 
csv.writer(sys.stdout).writerows([l[0], l[len(l)-1]]) 

,我參加了一個快捷方式,並表示輸入輸出文件被sys.stdinsys.stdout。您可能會用您在原始問題中創建的文件對象替換它們。 (如read_filewrite_file

然而,在我的情況,我可能只是運行它(如果我使用Linux)有:

$ ./foo.py <riskfactors.csv >best_and_worst.txt 
+0

他們並不真的希望我們使用CSV,但看起來不錯! –

相關問題