简体   繁体   English

如何读取 csv 并写入新的 CSV

[英]How to read a csv and write to a new CSV

python 2.7 input csv file python 2.7 输入csv文件

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

output format输出格式

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

The following should work for you given the following input (tab-delimited):给定以下输入(制表符分隔),以下内容应该适用于您:

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

Code:代码:

#!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)])

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM