By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,675 Members | 2,255 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,675 IT Pros & Developers. It's quick & easy.

How to use python to add a column to a csv file?

P: 27
Hello all!
I have a csv file which is usually has between 100 and 200 columns. I have a new column of data that I want to add to the csv file. I know if you open the file as "A" it will append the file, but I only know how to use it to add new rows to the document. not new columns.
Right now this code will write three columns of data:
Expand|Select|Wrap|Line Numbers
  1. myFile= open( "CC4.csv", "wb" )
  2. wtr= csv.writer( myFile )
  3. for blanka,s,q in zip(blanka,s,q):
  4.     wtr.writerow([blanka,s,q])
  5. myFile.close()
  6.  
Now assuming I have an array called "data" and I don't know how many columns are already written in the file, how can I add this new column to the file?

Thank you,
Ron Parker
May 9 '11 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Read the existing CSV file. Create a new array of data and append the new columns to each row. Then write the new array to disc. An example:
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. f = open('csv2.txt')
  4. data = [item for item in csv.reader(f)]
  5. f.close()
  6.  
  7. new_column = ["Col 1", "Line 1", "Line 2"]
  8.  
  9. new_data = []
  10.  
  11. for i, item in enumerate(data):
  12.     try:
  13.         item.append(new_column[i])
  14.     except IndexError, e:
  15.         item.append("placeholder")
  16.     new_data.append(item)
  17.  
  18. f = open('csv2B.txt', 'w')
  19. csv.writer(f).writerows(new_data)
  20. f.close()
May 10 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.