CSV read, edit specific field, write

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cswarwick
    New Member
    • Aug 2012
    • 2

    CSV read, edit specific field, write

    I am attempting to read a CSV file, edit a specific entry, then write back to disk. I am having trouble writing back to disk. I used split to separate fields and change. I can print the changes, but now I cannot write them back to the file. Can someone show me a quick simple example? (for simplicity I am using a small data file with 10 entries, seperated with commas, no headers)

    Thank you
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Let's say you read the csv file into a list of lists named dataList and you want to change the last element in the first line.
    Code:
    import csv
    
    dataList = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0],\
               [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0, 30.0, 30.0], \
               [0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0],\
               [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0]
    
    dataList[0][-1] = "XXXX"
    
    fn = r'D:\tmp\some.csv'
    f = open(fn, 'wb')
    w = csv.writer(f)
    
    w.writerows(dataList)
    f.close()

    Comment

    • cswarwick
      New Member
      • Aug 2012
      • 2

      #3
      Ok good. How would I allow user input to choose which entry?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        That depends on what you want. You could prompt the user using built-in function raw_input (input in Python 3.x) for the line and column to change and the new value, or you could build a GUI with Tkinter or other GUI toolkit with rows and columns of widgets where the user could edit whatever he wants.
        Last edited by bvdet; Aug 19 '12, 08:42 PM.

        Comment

        Working...