ömer sarı ömer sarı - 2 months ago 12
Python Question

Insert data in specific columns in csv file

I am trying to insert the data obtained from the date column. Columns headers are

date,day,month,year,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6
in the csv file. The columns
day, month, year
are currently empty.

I would like to insert the data obtained from the date by split method into these columns. How can l do that?

Here is an example data in csv file:

date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
1.01.1979 0.431 2.167 9.375 0.431 2.167 9.375
2.01.1979 1.216 2.583 9.162 1.216 2.583 9.162
3.01.1979 4.041 9.373 23.169 4.041 9.373 23.169
4.01.1979 1.799 3.866 8.286 1.799 3.866 8.286
5.01.1979 0.003 0.051 0.342 0.003 0.051 0.342
6.01.1979 2.345 3.777 7.483 2.345 3.777 7.483
7.01.1979 0.017 0.031 0.173 0.017 0.031 0.173


Here is my code:

import csv

dd=[]
mm=[]
yy=[]
with open('output2.csv') as csvfile:
reader = csv.DictReader(csvfile, fieldnames=("date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"), delimiter=';', quotechar='|')
next(reader) # skip header row
x = [row['date'] for row in reader]

for date_str in x:
day, month, year = date_str.split('.')
dd.append(day)
mm.append(month)
yy.append(year)

csvfile.close()

with open('output2.csv') as f:
fieldnames = ["date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"]
writer = csv.DictWriter(f, fieldnames=fieldnames,delimiter=';', quotechar='|')
for i in range(len(dd)):
writer.writerow({'day':dd[i]})
for i in range(len(mm)):
writer.writerow({'month':mm[i]})
for i in range(len(yy)):
writer.writerow({'year':yy[i]})


f.close()

Answer

You could just parse the CSV as follows. This reads all of your rows into a list, and then inserts the date componants into the empty columns.

import csv

with open('output2.csv', newline='') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)
    rows = list(csv_input)

with open('output2b.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output, delimiter=';', quotechar='|')
    csv_output.writerow(header)

    for row in rows:
        day, month, year = row[0].split('.')
        row[1:4] = [day, month, year]
        csv_output.writerow(row)

Giving you the following output:

date;day;month;year;pcp1;pcp2;pcp3;pcp4;pcp5;pcp6
1.01.1979;1;01;1979;0.431;2.167;9.375;0.431;2.167;9.375
2.01.1979;2;01;1979;1.216;2.583;9.162;1.216;2.583;9.162
3.01.1979;3;01;1979;4.041;9.373;23.169;4.041;9.373;23.169
4.01.1979;4;01;1979;1.799;3.866;8.286;1.799;3.866;8.286
5.01.1979;5;01;1979;0.003;0.051;0.342;0.003;0.051;0.342
6.01.1979;6;01;1979;2.345;3.777;7.483;2.345;3.777;7.483
7.01.1979;7;01;1979;0.017;0.031;0.173;0.017;0.031;0.173

Tested using Python 3.5.2

Comments