Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - add a new column to an existing csv file

I have a csv file with 5 columns and I want to add data in a 6th column. The data I have is in an array.

Right now, the code that I have will insert the data I would want in the 6th column only AFTER all the data that already exists in the csv file.

For instance I have:

wind, site, date, time, value
10, 01, 01-01-2013, 00:00, 5.1
89.6    ---> this is the value I want to add in a 6th column but it puts it after all the  data from the csv file

Here is the code I am using:

csvfile = 'filename'
with open(csvfile, 'a') as output:
    writer = csv.writer(output, lineterminator='
')
    for val in data:
        writer.writerow([val])

I thought using 'a' would append the data in a new column, but instead it just puts it after ('under') all the other data... I don't know what to do!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Appending writes data to the end of a file, not to the end of each row.

Instead, create a new file and append the new value to each row.

csvfile = 'filename'
with open(csvfile, 'r') as fin, open('new_'+csvfile, 'w') as fout:
    reader = csv.reader(fin, newline='', lineterminator='
')
    writer = csv.writer(fout, newline='', lineterminator='
')
    if you_have_headers:
        writer.writerow(next(reader) + [new_heading])
    for row, val in zip(reader, data)
        writer.writerow(row + [data])

On Python 2.x, remove the newline='' arguments and change the filemodes from 'r' and 'w' to 'rb' and 'wb', respectively.

Once you are sure this is working correctly, you can replace the original file with the new one:

import os
os.remove(csvfile) # not needed on unix
os.rename('new_'+csvfile, csvfile)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...