Reputation: 11
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
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
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:
pd.np.array(holidays)
converts holidays
to a numpy.array
.reshape((len(holidays) // 3, 3))
changes the structure of the array to three "columns"pd.DataFrame(data, columns=col_titles)
creates a pandas.Dataframe
from data and col_titles.to_csv("holidays.csv", index=False)
saves the dataframe to a CSV fileContent 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
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