I had a similar problem when trying to dump elements to a file as a dictionary. However, I imported json, http://docs.python.org/2/library/json.html checking this can be very useful. Remember to import json. This will provide the basis for dumping and loading data whenever you need. In this case, I dump and load the information into an empty dictionary. The try and except method is very useful if you want to use an empty dictionary. I find "r +" the most useful, as it will read and write the file.
def dump_data(): j = json.dumps(file.text, indent=4) with open("database.txt", "w") as f: f.write(j) def load_data(): try: with open("file.txt", "r+") as f: return json.load(fp=f) except IOError: return {}
MartianE
source share