First time here? We are a friendly community of Power Systems Engineers. Check out the FAQ!

Ask Your Question
1

writing to a particular cell using csv module in python

asked Mar 9 '13

Juan gravatar image

updated Mar 16 '13

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.

1 answer

Sort by » oldest newest most voted
0

answered Mar 9 '13

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)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.
Want to format code in your answer? Here is a one minute demo on Youtube

Add Answer

[hide preview]

Question Tools

Stats

Asked: Mar 9 '13

Seen: 30,693 times

Last updated: Mar 09 '13

Related questions