Как читать CSV и писать в новый CSV - PullRequest
0 голосов
/ 10 марта 2020

python 2.7 входной CSV-файл

person  alpha   beta    gamma
alex            1       2
bob     2               1
zac     1       2

выходной формат

Person  data            qty<2
alex    beta,gamma      beta
bob     alpha,gamma     gamma
zac     alpha,beta      alpha

1 Ответ

0 голосов
/ 11 марта 2020

Следующее должно работать для вас с учетом следующего ввода (с разделителями табуляции):

person  alpha   beta    gamma
alex            1       2
bob     2               1
zac     1       2

Код:

#!python2
import csv
import os

# open in binary mode per Python 2 csv docs
with open('x.csv','rb') as fin:

    csv_reader = csv.reader(fin,delimiter='\t')
    headers = next(csv_reader)
    item_names = headers[1:]    # collect names of data columns

    with open('y.csv','wb') as fout:
        csv_writer = csv.writer(fout,delimiter='\t')
        csv_writer.writerow(['Person','data','qty<2'])

        for row in csv_reader:
            person = row[0]
            items = row[1:] # list of the alpha/beta/gamma data

            data = []   # collect the names of non-empty data
            qtylt2 = [] # collect the names of <2 data

            for i,item in enumerate(items):
                if item:
                    data.append(item_names[i])
                    if int(item) < 2:
                        qtylt2.append(item_names[i])

            csv_writer.writerow([person,','.join(data),','.join(qtylt2)])

Вывод:

Person  data            qty<2
alex    beta,gamma      beta
bob     alpha,gamma     gamma
zac     alpha,beta      alpha
...