How do I add a new column of data to a csv file
I am reading a csv file into a variable data
like this:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.r开发者_Python百科eader(f))
data
is the entire csv file. How do I add an extra column to this data?
Short answer: open up the CSV file in your favourite editor and add a column
Long answer: well, first, you should use csv.reader
to read the file; this handles all the details of splitting the lines, malformed lines, quoted commas, and so on. Then, wrap the reader in another method which adds a column.
def get_file( start_file )
f = csv.reader( start_file )
def data( csvfile ):
for line in csvfile:
yield line + [ "your_column" ]
return data( f )
Edit
As you asked in your other question:
def get_file( start_file )
f = csv.reader( start_file )
def data( csvfile ):
for line in csvfile:
line[ 1 ] += "butter"
yield line
return data( f )
which you use like
lines = get_file( "my_file.csv" )
for line in lines:
# do stuff
data
is a list of lists of strings, so...:
for row, itm in zip(data, column):
row.append(str(itm))
of course you need column
to be the right length so you may want to check that, eg raise an exc if len(data) != len(column)
.
.append
a value to the end of each row in data
, and then use a csv.writer
to write the updated data.
精彩评论