Thread: File formats
View Single Post
Join Date: Dec 2006
Posts: 1,054
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 297
woooee woooee is online now Online
Veteran Poster

Re: File formats

 
0
  #3
Nov 19th, 2008
But now I want to be able to save it in file, preferably in form like this:

number;name
It's a simple combination so a common text file will work just fine. There is also the advantage of being able to verify what you have written to the file via any text processor. Note that dictionaries hash keys so they are not necessarily in key order.
  1. def read_from_file():
  2. after_d = {}
  3. fp = open("test.txt", "r")
  4. for rec in fp:
  5. rec=rec.strip()
  6. key, name = rec.split(";")
  7. after_d[int(key)]=name ## convert key back to an integer
  8. fp.close()
  9. return after_d
  10.  
  11.  
  12. def save_to_file(save_d):
  13. print "before saving to file", save_d
  14. fp = open("test.txt", "w")
  15. for key in save_d.keys():
  16. fp.write("%d;%s\n" % (key, save_d[key])) ## writes everything as a string
  17. fp.close()
  18.  
  19.  
  20. before_d = {}
  21. before_d[1]="Name 1"
  22. before_d[2]="Name 2"
  23. before_d[3]="Name 3"
  24. before_d[10]="Name 10"
  25. before_d[20]="Name 20"
  26.  
  27. save_to_file(before_d)
  28. after = read_from_file()
  29. print "read from file ", after
Last edited by woooee; Nov 19th, 2008 at 1:09 am.
Reply With Quote