Python: how to write data structure to file as text (not pickled)

Is there a way to write python data structs to a file as text.

eg. the app is running and has a variable / object: OPTIONS = ('ON', 'OFF',)

I need to write / concatenate the OPTIONS tuple into another file, not as a pickled object, but as text, verbatim: OPTIONS = ('ON', 'OFF',)

I could traverse the tuple and write the elements one by one to the target file, but wondered if there was an easier way.

note: if I do "direct" recording, I get the following:

fout.write(OPTIONS)
 ... 
TypeError: argument 1 must be string or read-only character buffer, not tuple

      

+2


source to share


3 answers


You can use repr (schedule works well with things that have a method __repr__()

):



>>> OPTIONS=('ON', 'OFF', )
>>> "OPTIONS="+repr(OPTIONS)
"OPTIONS=('ON', 'OFF')"

      

+4


source


fout.write(str(OPTIONS))

does what you want in this case, but no doubt it won't in many others; repr

instead str

may be closer to your desires (but then again, it may not be, since you are expressing them so vaguely and generally beyond this single example).



+1


source


I don't know your scope, but you can use a different serialization / persistence system like JSON or Twisted Jelly which are more human readable (others like YAML ).

I used jelly in some project for settings files. It's very easy to use, but you have to use the repr () function to store the data in human readable form, and then eval () to read it. So don't do this at all, because there is a security risk with eval ().

Here's a sample code that pre-qualifies the view (adds indentation):

VERSION = 'v1.1'

def read_data(filename):
    return unjelly(eval(open(filename, 'r').read().replace('\n', '').replace('\t', '')))

def write_data(filename, obj):
    dump = repr(jelly(obj))
    level = 0
    nice_dump = ['%s\n' % VERSION]
    for char in dump:
        if char == '[':
            if level > 0:
                nice_dump.append('\n' + '\t' * level)
            level += 1
        elif char == ']':
            level -= 1
        nice_dump.append(char)
    open(filename, 'w').write(''.join(nice_dump))

      

+1


source







All Articles