且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python在CSV上添加新列

更新时间:2023-11-18 22:52:28

您可以将 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")