2015-11-05 165 views
1

我遇到了一個小問題。我正在嘗試創建一個腳本,它需要大量(〜2GB)csv文件(id,integer,integer),按第一個整數對它們進行排序,然後將其寫入新文件的頂部x行(由用戶定義)。Python - 用於將某些行寫入新文件的CSV模塊

我能夠得到的排序功能,按要求工作,並提取頂部X行的作品也,但我不能解決如何獲得這個輸出寫入CSV。 要檢查它一直在工作,我已經包括一個打印功能,它似乎工作得很好。

我覺得我錯過了csv模塊中的一個真正的基本概念,但我無法弄清楚它是什麼!

import csv 
import operator 

def csv_to_list(csv_file, delimiter=','): 

    with open(csv_file, 'r') as csv_con: 
     reader = csv.reader(csv_con, delimiter=delimiter) 
     return list(reader) 

def sort_by_column(csv_cont, col, reverse=True): 

    header = csv_cont[1] 
    body = csv_cont[1:] 
    if isinstance(col, str): 
     col_index = header.index(col) 
    else: 
     col_index = col 
    body = sorted(body, 
      key=operator.itemgetter(col_index), 
      reverse=reverse) 
    #body.insert(0, header) 
    return body 

def print_csv(csv_content): 
    for row in csv_content: 
     row = [str(e) for e in row] 
     print('\t'.join(row)) 

def write_csv(dest, csv_cont): 
    with open(dest, 'w') as out_file: 
     writer = csv.writer(out_file, delimiter=',') 
     for row in csv_cont: 
      writer.writerow(row) 

csv_cont = csv_to_list(input_hep.csv) 
row_count = sum(1 for row in csv_cont) 
num_rows = int(input("Skim size?: ")) 
output_file = input("Output: ") 

csv_sorted = sort_by_column(csv_cont, 1) 
for row in range(num_rows): 
    print(csv_sorted[row]) 

我的主要想法是嘗試:

with open(output_file+'.csv','w') as f: 
    writer = csv.writer(f, delimiter =',') 
    for row in range(num_rows): 
     writer.writerow(row) 

但後來我得到一個 「_csv.Error:迭代預期,不是int」 的錯誤。我明白了爲什麼,但我很努力地理解如何讓輸出(如打印)在csv中寫入。 任何提示或指針,將不勝感激。

回答

1

如果陣列是一個多維的列表,你可以使用writerows直接不反覆

with open(output_file+'.csv','w') as f: 
    writer = csv.writer(f, delimiter =',') 
    writer.writerows(sorted_csv_cont) 

假設你的列表在以下格式

[ 
    ["R1_C1","R1_C2"], 
    ["R2_C1","R2_C2"] 
] 
0

我只是寫爲csv這樣

hs = open(filepath,"w+") 
for mline in rows: 
    hs.write(",".join(mline)+"\r") 

但我加載了CSV作爲一個多維列表與在CSV代表行的每一行,並具有項目,在代表一個項目的列表該行

0

Writerow功能需要一個迭代的對象像列表