使用Python在CSV上添加新列 [英] Adding a new column on CSV with Python

查看:559
本文介绍了使用Python在CSV上添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数字列表: ['Number',1,2,3,4]

如果我有以下CSV文件:

If I have the following CSV file:

`Name`    
`First`
`Second`
`Third`
`Fourth`

如何添加列表数字使其看起来像这样:

How do I add my list of numbers to it and make it look like this:

`Name    Number`
`First   1`
`Second  2`
`Third   3`
`Fourth  4`


推荐答案

您可以将 fileinput.input inplace = True 一起使用,以修改原始内容文件:

You can use fileinput.input with inplace=True to modify the original file:

import fileinput
import sys
l =['Number', 1,2,3,4]
for ind, line in enumerate(fileinput.input("in.csv",inplace=True)):
    sys.stdout.write("{} {}\n".format(line.rstrip(), l[ind]))

输入:

Name    
First
Second
Third
Fourth

输出:

Name Number
First 1
Second 2
Third 3
Fourth 4

或写入临时文件并使用shutil.move移动以替换原始文件:

Or write to a tempfile and move with shutil.move to replace the original file:

l =['Number', 1,2,3,4]
from shutil import move
from tempfile import NamedTemporaryFile
with open('in.csv') as csvfile, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    r = csv.reader(csvfile)
    wr = csv.writer(temp,delimiter=" ")
    for row,new in zip(r,l):
        wr.writerow(row+[new])

move(temp.name,"in.csv")

这篇关于使用Python在CSV上添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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