473,387 Members | 3,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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

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
1 47438
bvdet
2,851 Expert Mod 2GB
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

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

Similar topics

4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
0
by: Christopher DeMarco | last post by:
Hi all... ...I've got a Python script running on a bunch of boxen sharing some common NFS-exported space. I need (not want :) to lock files for writing, and I need (not want :) to do it safely...
4
by: news | last post by:
I've just started to test/learn python. I've got Linux > mandrake9 > python & documentation. What I'll initially want to be doing needs file I/O, so I wanted to confirm file I/O early in my...
2
by: pycircle | last post by:
From a python module, I want to run any.py module, to open it in the shell, just like if I were in IDLE editor and selecting EDIT / Run Module. I have tried a lot of things, including importing a...
2
by: yinglcs | last post by:
How to modify the source of a python file inside a python egg file? I can see the file by unzipping it, but how can I package it back as a python egg file after my modification. Thank you.
6
by: Gilles Ganault | last post by:
Hello I'm sure there's a much easier way to read a two-column, CSV file into an array, but I haven't found it in Google. Should I use the Array module instead? ========= a = i = 0
2
by: yinglcs | last post by:
Hi, I am trying to use python for file processing. Suppose I have a file like this: I want to build a Hashmap between the line "begin_QOS_statistics" and "end_QOS_statistics" and for each line...
4
by: loial | last post by:
I am writing a file in python with writelines f = open('/home/john/myfile',"w") f.writelines("line1\n") f.writelines("line2\n") f.close() But whenever I try to do anything with the file in...
2
by: BAnderton | last post by:
Greetings from beautiful Tucson, Arizona. Question: Is there a way in Python to determine what all file identifiers have been opened by Python, and to close them all? Why I ask: I learned...
0
by: vmars956 | last post by:
Greetings: The following files are all ' *.file ' . This seems wrong. They all contain similar to this: #!/usr/bin/env python from wx.tools.XRCed.xrced import main main() What are they,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.