user3112327
user3112327

Reputation: 305

How to add to a dictionary through my text file

My text file looks like this:

{'testyear3': 20, 'testyear6': '0', 'testyear5': '0', 'testyear4': '0'}

It will always look like this, I cannot change the order of the text file or how it is placed as during my program, I write a dictionary that is made to the text file with the code

with open ("totals.txt", 'w') as f27:
  f27.write(str(totaldict))

therefore at the end of the program the text file always reverts to the order above. How would I go about writing the text file to a dictionary in the format that it is in? Or would I have to change the way I write to the text file?

Upvotes: 0

Views: 134

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123520

You want to change the way you write your dictionary to a text file. The JSON format would be much easier to process (with the json module):

import json

# saving
with open("totals.txt", 'w') as f27:
    json.dump(totaldict, f27)

# loading
with open("totals.txt", 'r') as f27:
    totaldict = json.load(f27)

However, a dictionary does not maintain any specific order; they are unordered collections by design. If you wanted to store items in a specific order, you'd have to either use a different data structure (like a list), or sort your information and use a custom format.

Upvotes: 4

luk32
luk32

Reputation: 16080

I use python's native parser:

def read_dict( fname, src = None):
  if src is None :
    src = StringIO.StringIO(fname)
  src_global = { }
  locals =  {}
  comp_obj = compile(src, fname, 'exec')
  eval(comp_obj, src_global, locals)
  return locals

This loads a file, and basically parses it, and then returns local variables created during parsing.

You would need to prepend your code with some variable name, and then return this variable instead of locals.

Of course it might be an overkill, but I have file with few dictionaries in format of python script. I guess it's one way to do it.

Upvotes: 0

Related Questions