2014-10-28 129 views
1

大家好,非常感謝您的閱讀。我正在嘗試創建一個python腳本,用於快速打印出我的.csv文件的某些列。數據庫外觀如下.csvPython打印.csv的某些列

Song_Name,File_Name,Artist_Name,Artist_ID 
Song1,filename1,artistname,artist001 
Song1,filename1,artistname,artist001 
Song1,filename1,artistname,artist001 
Song1,filename1,artistname,artist001 

,我試圖創建一個新的CSV僅具有

Song_Name,Artist_ID 
Song1,artist001 
Song1,artist001 
Song1,artist001 
Song1,artist001 
我使用此代碼

import csv 

with open('convert.csv','rb') as i: 
    with open('converted.csv','wb') as o: 
     r = csv.DictReader(i) 
     w = csv.DictWriter(o,'Song_Name Artist_ID'.split(),extrasaction='ignore') 
     w.writeheader() 
     for a in r: 
      w.writerow(a) 

結果是題爲轉換銀行的.csv。我究竟做錯了什麼?

+0

我想你的解決方案,它爲我工作。 @ inspectorG4dget的答案更快,但不會修復代碼中的任何錯誤。 – tdelaney 2014-10-28 22:36:50

回答

1
with open('convert.csv','r') as infile, open('converted.csv','w') as outfile: 
    writer = csv.writer(outfile, delimiter=',') 
    for row in csv.reader(infile): 
     writer.writerow([row[0], row[-1]]) 
2

你可以使用Python petl庫(Python中提取轉換加載) 比方說,你有第一個表中的CSV文件(你也可以直接使用petl數據庫加載)。然後,您只需加載它並執行以下操作。

#Load the table 
table1 = fromcsv('table1.csv') 
# Alter the colums 
table2 = cut(table1, 'Song_Name','Artist_ID') 
#have a quick look to make sure things are ok. Prints a nicely formatted table to your console 
print look(table2) 
# Save to new file 
tocsv(table2, 'new.csv') 

在這個快速的介紹請看:http://petl.readthedocs.org/en/latest/case_study_1.html