Ask Your Question
1

writing to a particular cell using csv module in python

asked 2013-03-09 09:03:07 -0500

Juan gravatar image

updated 2013-03-15 19:58:02 -0500

JervisW gravatar image

I have to write a value of MW of many lines to a particular cell in my csv file. I can see there is a csvwriter.writerow(row) method to write an entire row, but I am not seeing anything to write a value to a particular cell.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2013-03-09 16:10:01 -0500

JervisW gravatar image

The csv.writer object is an improved version of this simple code:

data = [('Bus Number', 'MW'),
        ('3', '20.4'),
        ('4', '20.5')]

csvfile = open('generation.csv', 'wb')
for row in data:
    line = ','.join(row)
    csvfile.write(line + '\n')

See how it writes each row line by line? There isn't a way to change one character without re-writing the whole file.

The way to change a particular cell

Change the cell in your data variable. For example, you'd like to change B3 in the data variable above from '20.5' to '20.6'. Then re-write the file.

# row 3, column 2
data[2][1] = '20.6'

writer = csv.writer(open('generation.csv', 'wb'))
writer.writerows(data)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

[hide preview]

Question Tools

Stats

Asked: 2013-03-09 09:03:07 -0500

Seen: 30,625 times

Last updated: Mar 09 '13

Related questions