社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中使用writerow附加到我的csv

Maths12 • 5 年前 • 2028 次点击  

我有一张excel表格,只有一列,标题是Name,下面的行是Jerry。我要做的就是用python加上标题:a g e,然后在下面加一行,比如14。

我该怎么做?

with open('simpleexcel.csv', 'r') as f_input:  # Declared variable f_input to open and read the input file
    input_reader = csv.reader(f_input)  # this will iterate ober lines from input file

    with open('Outputfile.csv', "w", newline='') as f_output:  # opens a file for qwriting in this case outputfile
        line_writer = csv.writer(f_output) #If csvfile is a file object, it should be opened with newline=''
        for line in input_reader: #prints every row
            line_writer.writerow(line+['14'])

相反,我得到14分和14分,我不知道怎么得到另一个头球

我首先要做的是

Name 
Jerry

Name   Age 
Jerry  14 

相反,我得到:

Name   14
Jerry  14 

我怎样才能修改上面的代码?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54143
 
2028 次点击  
文章 [ 2 ]  |  最新文章 5 年前
rahul
Reply   •   1 楼
rahul    5 年前

我不知道你想在这里完成什么,但对于你的例子来说,这是可以使用的。

import csv

with open('simpleexcel.csv', 'r') as f_input:
    input_reader = list(csv.reader(f_input))

input_reader[0].append('Age')
for row in input_reader[1:]:
    row.append(14)


with open('Outputfile.csv', "w", newline='') as f_output:
    csv.writer(f_output).writerows(input_reader)

Name
Jerry

输出:

Name,Age
Jerry,14
Rakesh
Reply   •   2 楼
Rakesh    5 年前

使用 next(input_reader) 获取标题,然后附加新列名并将其写回csv。

with open('simpleexcel.csv', 'r') as f_input:  # Declared variable f_input to open and read the input file
    input_reader = csv.reader(f_input)  # this will iterate ober lines from input file

    with open('Outputfile.csv', "w", newline='') as f_output:  # opens a file for qwriting in this case outputfile
        line_writer = csv.writer(f_output) #If csvfile is a file object, it should be opened with newline=''
        line_writer.writerow(next(input_reader) + ["Age"]))  #Write Header
        for line in input_reader: #prints every row
            line_writer.writerow(line+['14'])