import csv
from itertools import zip_longest
def readcsv(filepath):
data = {}
with open(filepath,'r') as f:
reader = csv.reader(f)
for row in reader:
if row[0] not in data:
data[row[0]] = []
data[row[0]].append(row[-1])
return data
def writecsv(filepath, data):
with open(filepath, 'w', newline='') as f:
writer = csv.DictWriter(f, data.keys())
writer.writeheader()
write_datas = []
for each in zip_longest(*data.values(), fillvalue=''):
write_datas.append(dict(zip(data.keys(), each)))
writer.writerows(write_datas)
if __name__ == '__main__':
result = readcsv('./test.csv')
writecsv('./result.csv', result)
|