写一个额外的列WITH头 [英] Writing an extra column WITH header

查看:106
本文介绍了写一个额外的列WITH头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这个:



2个变量:
varHeader:ExtraColumn
varContent:ToBeFilledIn

  writer.writeheader()
在阅读器中:
writer.writerow(line)

这一切都很好。问题是,我有2个变量,varHeader和varContent。我在writer.writeheader之前失败了:


  1. 我需要添加一个额外的列作为标题ExtraColumn,




  2. 每个'行'需要将varContent的值添加到新创建的列 $ b

    虽然这看起来很简单,但是它让我想起来,我不能做到。猜猜这是一个典型的周五病; - )



    感谢伙伴,



    >

    解决方案

    这是你想要的吗?

      from csv import DictReader,DictWriter 

    with open ...:
    reader = DictReader(in_f)
    writer = DictWriter(out_f,['ExtraColumn'] + reader。 fieldnames)
    writer.writeheader()
    在阅读器中的行:
    line ['ExtraColumn'] = varContent
    writer.writerow(line)


    at the moment I have this:

    2 variables: varHeader: ExtraColumn varContent: ToBeFilledIn

            writer.writeheader()
            for line in reader:
                writer.writerow(line)
    

    And that all works fine. Problem is that I have 2 variables, varHeader and varContent. And what am I failing at:

    1. before writer.writeheader, I need to add an extra column with as title ExtraColumn, which is the content of the varHeader variable.
    2. each 'line' needs to add the value of varContent to the newly created column

    Although this seemed simple to me, it is blowing my mind, I can't get it done. Guess it's a typical friday disease ;-)

    Thanks mates,

    regard from a newbie.

    解决方案

    Is this what you want?

    from csv import DictReader, DictWriter
    
    with open ...:
        reader = DictReader(in_f)
        writer = DictWriter(out_f, ['ExtraColumn'] + reader.fieldnames)
        writer.writeheader()
        for line in reader:
            line['ExtraColumn'] = varContent
            writer.writerow(line)
    

    这篇关于写一个额外的列WITH头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆