2017-09-24 89 views
0

如何將下列列表拆分爲多行(3行)並使用python寫入csv文件。使用python將多行記錄寫入csv文件

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW'] 

以下代碼將所有值寫入csv中的單個列。

Title = ('date', 'name','state') 

with open(fileName,"w") as output: 
    writer = csv.writer(output,lineterminator='\n') 
    for val in lstAll: 
     writer.writerow([val]) 

回答

0

您可以使用列表分片處理中的3塊列表:

with open(fileName, "w") as output: 
    writer = csv.writer(output, lineterminator='\n') 
    for i in range(0, len(lst), 3)): 
     writer.writerow(lst[i:i+3]) 
0

這裏有一種冗長例子,顯示列表解釋是如何工作的:

with open('outfile.csv', 'w') as outfile: 
    writer = csv.writer(outfile) 
    rows = [[holiday, holidays[i+1], holidays[i+2]] for i, holiday in enumerate(holidays) if i % 3 == 0] 
    for row in rows: 
     writer.writerow(row) 
+0

這裏沒有列表切片。 –

+0

更新,謝謝。 –

2

一solution using pandas

import pandas as pd 

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW'] 
col_titles = ('date', 'name','state') 

data = pd.np.array(holidays).reshape((len(holidays) // 3, 3)) 

pd.DataFrame(data, columns=col_titles).to_csv("holidays.csv", index=False) 

其中:

  1. pd.np.array(holidays)轉換holidaysnumpy.array
  2. .reshape((len(holidays) // 3, 3))改變陣列的結構到三個 「列」
  3. pd.DataFrame(data, columns=col_titles)從數據創建一個pandas.Dataframe和col_titles
  4. .to_csv("holidays.csv", index=False)保存數據幀到CSV文件

01的含量:

date,name,state 
2017-01-01,New Year's Day,NSW 
2017-01-02,New Year's Day (Observed),NSW 
2017-01-26,Australia Day,NSW 
2017-04-14,Good Friday,NSW 
2017-04-15,Easter Saturday,NSW 

請注意,如果您在使用to_csvindex=False指數將不包括在內。