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

CSV read, edit specific field, write

P: 2
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
Aug 19 '12 #1

✓ answered by bvdet

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.
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. dataList = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0],\
  4.            [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0, 30.0, 30.0], \
  5.            [0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0],\
  6.            [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0]
  7.  
  8. dataList[0][-1] = "XXXX"
  9.  
  10. fn = r'D:\tmp\some.csv'
  11. f = open(fn, 'wb')
  12. w = csv.writer(f)
  13.  
  14. w.writerows(dataList)
  15. f.close()

Share this Question
Share on Google+
3 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
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.
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. dataList = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0],\
  4.            [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0, 30.0, 30.0], \
  5.            [0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 30.0, 30.0],\
  6.            [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 15.0, 20.0, 25.0]
  7.  
  8. dataList[0][-1] = "XXXX"
  9.  
  10. fn = r'D:\tmp\some.csv'
  11. f = open(fn, 'wb')
  12. w = csv.writer(f)
  13.  
  14. w.writerows(dataList)
  15. f.close()
Aug 19 '12 #2

P: 2
Ok good. How would I allow user input to choose which entry?
Aug 19 '12 #3

bvdet
Expert Mod 2.5K+
P: 2,851
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.
Aug 19 '12 #4

Post your reply

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