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

2024-05-14 08:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel表格,只有一列,标题是名称,下面的一行是Jerry。我所要做的就是使用python将其附加到标题:Age,然后在下面的一行加上,例如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 

如何输入上述代码


Tags: csvname标题inputageaswithline
2条回答

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

Ex:

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'])

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

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

相关问题 更多 >

    热门问题