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.
def read_from_file():
after_d = {}
fp = open("test.txt", "r")
for rec in fp:
rec=rec.strip()
key, name = rec.split(";")
after_d[int(key)]=name ## convert key back to an integer
fp.close()
return after_d
def save_to_file(save_d):
print "before saving to file", save_d
fp = open("test.txt", "w")
for key in save_d.keys():
fp.write("%d;%s\n" % (key, save_d[key])) ## writes everything as a string
fp.close()
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"
before_d[10]="Name 10"
before_d[20]="Name 20"
save_to_file(before_d)
after = read_from_file()
print "read from file ", after
Last edited by woooee; Nov 19th, 2008 at 1:09 am.
Reputation Points: 741
Solved Threads: 691
Nearly a Posting Maven
Offline 2,302 posts
since Dec 2006