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

How to use python to write to a specific cell in a csv file?

P: 27
Hello all!

I have a list of 5 characters

Expand|Select|Wrap|Line Numbers
  1. >>> li
  2. [1,2,3,4,5]
  3.  
I want to write only certain elements of this list to specific cells in a csv file.

Right now what I am doing is this:
Expand|Select|Wrap|Line Numbers
  1. myFile= open( "FILE.csv", "wb" )
  2. wtr= csv.writer( myFile )
  3. for li in zip(li):
  4.     dRow=[li]
  5.     wtr.writerow(dRow)
  6.  
  7. myFile.close()
  8.  
However, this just writes the entire list in column 1. Instead If I want to just write element 2 of the list in column 3 and row 5, how would I do that?

Thank you,
Ron Parker

Ok, I realize this is kind of a silly question because csv files i guess do not technically have cells. However, how would I do this for excel?
Feb 3 '11 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
The individual positions in a CSV file actually represent cells in a spreadsheet. To interact with an Excel spreadsheet, look at the xlrd and xlwt modules. Note that xlwt is for generating spreadsheets, not for writing to existing sheets. The following interaction is similar to what the CSV module would do for simple CSV data.
Initialize the data list (a list of lists representing columns and rows)
Modify a specific element using index assignment
Format the list of lists into a string suitable for writing to a CSV file
Expand|Select|Wrap|Line Numbers
  1. >>> data = [[0,0,0,0,0] for line in range(10)]
  2. >>> data
  3. [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
  4. >>> data[2][4] = [1,2,3,4,5][2]
  5. >>> data
  6. [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 3], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
  7. >>> dataStr = "\n".join([",".join([str(num) for num in item]) for item in data])
  8. >>> print dataStr
  9. 0,0,0,0,0
  10. 0,0,0,0,0
  11. 0,0,0,0,3
  12. 0,0,0,0,0
  13. 0,0,0,0,0
  14. 0,0,0,0,0
  15. 0,0,0,0,0
  16. 0,0,0,0,0
  17. 0,0,0,0,0
  18. 0,0,0,0,0
  19. >>> 
Feb 4 '11 #2

P: 27
Thank you so much! However, I still have a question regarding you code. If i now write dataStr to a csv file, all of the cells that are supposed to be blank will have a "0" inside them. Is that easily fixable?
Feb 5 '11 #3

P: 27
Never mind, i think i got it. I just replaced 0 with "" when making the data variable. Thanks again!
Feb 5 '11 #4

Post your reply

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