使用python将列表写入csv文件中的多行

时间:2017-09-24 13:58:01

标签: python python-2.7 python-3.x csv

如何将以下列表拆分为多行(3行)并使用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])

3 个答案:

答案 0 :(得分:3)

使用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)holidays转换为numpy.array
  2. .reshape((len(holidays) // 3, 3))将数组的结构更改为三个"列"
  3. pd.DataFrame(data, columns=col_titles)从数据和col_titles
  4. 创建pandas.Dataframe
  5. .to_csv("holidays.csv", index=False)将数据框保存为CSV文件
  6. holidays.csv的内容:

    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
    

    请注意,如果您在index=False中使用to_csv,则不会包含该索引。

答案 1 :(得分: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])

答案 2 :(得分: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)