2016-04-02 74 views
1

我有超過200個文件,我想通過列列表CLNAME值來劃分,並保持頭在所有files.I也想保存這與文件OriginalFileName-clName.txt鴻溝csv文件

ID Plate Well  ctr  clID  clName 
21 5  C03  1  50012  COL 
21 5  C03  1  50012  COL 
21 5  C03  1  50012  COL 
21 5  C04  1  50012  IA 
21 5  C04  1  50012  IA 
21 5  C05  1  50012  ABC 


import csv 
from itertools import groupby 

for key, rows in groupby(csv.reader(open("file.csv")), 
         lambda row: row[7]): 
    with open("%s.txt" % key, "w") as output: 
     for row in rows: 
      output.write(",".join(row) + "\n") 

我遇到的問題是列不會總是被稱爲clName,它可以被稱爲clName,cll_n,c_Name。有時這將是第7列,其他時間列5或9.

我所知道的是按列值分隔文件,但不保留標題,我必須檢查每個文件以查找其列5 ,7,9等。

有沒有辦法讓我檢查名稱列表中的列名稱,以及何時發現其中一個名稱按該列值拆分文件?

例如數據 https://drive.google.com/file/d/0Bzv1SNKM1p4uell3UVlQb0U3ZGM/view?usp=sharing

謝謝

+0

你的意思是你想添加最後一個列標題到文件末尾嗎?如何確定第5,7或9欄中是否有正確的名稱? –

+0

不需要在每個文件中保留標題。然後保存帶有列值和原始文件名的文件,如originalfile-COL.txt –

回答

2

使用csv.DictReadercsv.DictWriter代替。這是一個應該指向正確方向的輪廓。

special_col = ['cll_n', 'clName'] 

with open('myfile.csv', 'r') as fh: 
    rdr = csv.DictReader(fh) 

    # now we need to figure out which column is used 
    for c in special_col: 
     if c in rdr.fieldnames: 
      break # found the column name 
    else: 
     raise IOError('No special column in file') 

    # now execute your existing code, but group by the 
    # column using lambda row: row[c] instead of row 7 
    call_existing_code(rdr, c) 


def call_existing_code(rdr, c): 
    # set up an output file using csv.DictWriter; you can 
    # replace the original column with the new column, and 
    # control the order of fields 

    with open('output.csv', 'w') as fh: 
     wtr = csv.DictWriter(fh, fieldnames=['list', 'of', 'fields']) 
     wtr.writeheader() 

     for row in groupby(rdr, lambda r: r[c]): 

      # [process the row as needed here] 

      wtr.writerow(row)