imsteve
imsteve

Reputation: 11

writing a list to multiple rows into csv file using python

How to split following list to multiple rows (3 rows) and write in to a csv file using python.

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']

Following code write all values to single column in a csv.

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

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

Upvotes: 0

Views: 3577

Answers (3)

Ben Quigley
Ben Quigley

Reputation: 737

Here's a kind of verbose example that shows how the list interpretation works:

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)

Upvotes: 0

FabienP
FabienP

Reputation: 3158

A 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)

Where:

  1. pd.np.array(holidays) converts holidays to a numpy.array
  2. .reshape((len(holidays) // 3, 3)) changes the structure of the array to three "columns"
  3. pd.DataFrame(data, columns=col_titles) creates a pandas.Dataframe from data and col_titles
  4. .to_csv("holidays.csv", index=False) saves the dataframe to a CSV file

Content of 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

Note that the index will not be included if you use index=False in to_csv.

Upvotes: 3

Eugene Yarmash
Eugene Yarmash

Reputation: 150128

You can use list slicing to process the list in chunks of 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])

Upvotes: 0

Related Questions