【问题标题】:How to read a csv and write to a new CSV如何读取 csv 并写入新的 CSV
【发布时间】:2020-06-22 17:29:51
【问题描述】:

蟒蛇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

【问题讨论】:

  • 请正确格式化您的代码,并将格式发布为文本。
  • 请说明问题所在,并提供minimal reproducible example。顺便说一句,您为什么使用 Python 2?
  • 嗨,我正在使用 python 2.7,因为我是 stackoverflow 的新手,我无法进行正确的编辑以显示数据的外观
  • @Roy 是的,我尝试编辑代码,但我不完全确定它应该是什么样子。为什么不能分享? 我正在使用 python 2.7 对不起,如果我的评论不清楚,我在问你为什么使用那个版本。
  • @Roy 不使用制表符,例如。它们在网站上效果不佳。您的代码的一个问题是它没有将制表符指定为分隔符。 CSV 默认为逗号。

标签: python python-2.7 csv parsing


【解决方案1】:

给定以下输入(制表符分隔),以下内容应该适用于您:

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

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2018-03-19
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多