I have several CSV files that look like this:
Input
Name Code
blackberry 1
wineberry 2
rasberry 1
blueberry 1
mulberry 2
I would like to add a new column to all CSV files so that it would look like this:
Output
Name Code Berry
blackberry 1 blackberry
wineberry 2 wineberry
rasberry 1 rasberry
blueberry 1 blueberry
mulberry 2 mulberry
The script I have so far is this:
import csv
with open(input.csv,'r') as csvinput:
with open(output.csv, 'w') as csvoutput:
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
writer.writerow(row+['Berry'])
(Python 3.2)
But in the output, the script skips every line and the new column has only Berry in it:
Output
Name Code Berry
blackberry 1 Berry
wineberry 2 Berry
rasberry 1 Berry
blueberry 1 Berry
mulberry 2 Berry
I don't see where you're adding the new column, but try this:
Maybe something like that is what you intended?
Also, csv stands for comma separated values. So, you kind of need commas to separate your values like this I think:
I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:
Check out Pandas Website for more information!
Contents of
output.csv
:This code will suffice your request and I have tested on the sample code.
This should give you an idea of what to do:
Edit, note in py3k you must use
next(r)
Thanks for accepting the answer. Here you have a bonus (your working script):
Please note
lineterminator
parameter incsv.writer
. By default it is set to'\r\n'
and this is why you have double spacing.writerows
. If your file is very, very big this probably is not a good idea (RAM) but for normal files I think it is faster because there is less I/O.As indicated in the comments to this post, note that instead of nesting the two
with
statements, you can do it in the same line:with open('C:/test/test.csv','r') as csvinput, open('C:/test/output.csv', 'w') as csvoutput:
I used pandas and it worked well... While I was using it, I had to open a file and add some random columns to it and then save back to same file only.
This code adds multiple column entries, you may edit as much you need.
If you want that cell value doesn't gets copy, so first of all create a empty Column in your csv file manually, like you named it as Hours then, Now for this you can add this line in above code,
or simply we can, without adding the manual column, we can
I Hope it helps.