2014-10-29 285 views
2

你好,我有一個數據庫,我試圖快速從一個.csv文件。Python添加空白/空列。 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 

這就是我需要它的樣子。

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

什麼是最好的方法來做到這一點。謝謝。

+0

剛剛插入的每一行通過索引和寫入 – 2014-10-29 02:01:57

+0

帕德里克的評論是不是非常有幫助,但理所當然的,所以沒有想到的是告訴你,你已經什麼試着先做。你會用你試過的東西更新我們嗎? – ericmjl 2014-10-29 02:07:03

+0

@ericmjl,它怎麼沒有幫助?這是需要什麼做 – 2014-10-29 02:10:54

回答

-1

這是我的答案來幫助你。

首先,我建議在IPython的環境中使用熊貓,而不是Python的內置一個CSV閱讀器。熊貓提供了一些強化表格數據的功能。這就是說,你可以使用Python內置的CSV模塊做些什麼。

with open('data.csv', 'r') as infile: 
    with open('data_out.csv', 'w') as outfile: 
     for line in csv.reader(infile): 
      newline = [] 
      for element in line: 
       if line.index(element) in [1, 3]: # crucial part here: identify where you want to make insertions 
        newline.append(' ') 
       newline.append(element) 
      print(newline) 
      csv.writer(outfile).writerow(newline) 

至於是否與去熊貓與簡單地遍歷文件,它八九不離十取決於評估 - 從我自己的經驗,我已經通過加載一個大的CSV文件到大熊貓發現相當大的內存開銷,所以我切換使用Python的內置模塊來處理我的數據文件。也就是說,我可能還沒有足夠深入地掌握熊貓。 :-)

0

正如帕德里克·坎寧安說just insert into each row by index and write

with open('data.csv', 'r') as fdin, open('out.csv', 'w') as fdout: 
    for line in csv.reader(fdin): 
     # insert into each row by index 
     line.insert(1, '') 
     # and write 
     csv.writer(fdout).writerow(newline)