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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ronparker
    New Member
    • Aug 2010
    • 27

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

    Hello all!

    I have a list of 5 characters

    Code:
    >>> li
    [1,2,3,4,5]
    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:
    Code:
    myFile= open( "FILE.csv", "wb" )
    wtr= csv.writer( myFile )
    for li in zip(li):
    	dRow=[li]
    	wtr.writerow(dRow)
    	
    myFile.close()
    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?
    Last edited by Niheel; Feb 4 '11, 11:07 PM. Reason: merged second question with original question
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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
    Code:
    >>> data = [[0,0,0,0,0] for line in range(10)]
    >>> data
    [[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]]
    >>> data[2][4] = [1,2,3,4,5][2]
    >>> data
    [[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]]
    >>> dataStr = "\n".join([",".join([str(num) for num in item]) for item in data])
    >>> print dataStr
    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
    >>>

    Comment

    • ronparker
      New Member
      • Aug 2010
      • 27

      #3
      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?

      Comment

      • ronparker
        New Member
        • Aug 2010
        • 27

        #4
        Never mind, i think i got it. I just replaced 0 with "" when making the data variable. Thanks again!

        Comment

        Working...