2

I would like to create a "metadata" file for several Python objects I have built and was wondering if there was an elegant way to write a subset of these attributes to a .txt file. Ideally, the .txt file would have the following formatting:

object.Name = thisistheobjectname object.Value = thisistheobjectvalue etc...
4
  • 1
    Why not just use pickle to serialize the object to a file? Commented Jul 8, 2015 at 14:47
  • 1
    Industry standard these days is JSON of you want something human readable. Commented Jul 8, 2015 at 14:51
  • Great, thanks. Can I pickle only a subset of object attributes? Commented Jul 8, 2015 at 14:52
  • How do you intend on determining and defining the subset? Commented Jul 8, 2015 at 16:35

3 Answers 3

4

If your goal is to reuse this object later on, then don't reinvent the wheel and use pickle. But if your goal is to just get objects variables in a nice looking txt file then you can leverage __dict__ of the object

You can ether store it in JSON or convert it to what ever works for you:

For example:

import json

class Foo(object):
  def __init__(self, name, value):
    self.name = name
    self.value = value

myfoo = Foo('abc', 'xyz')
with open('foo.txt', 'w') as f:
  f.write(' '.join(["myfoo.%s = %s" % (k,v) for k,v in myfoo.__dict__.iteritems()]))

Will result in something like:

myfoo.name = abc myfoo.value = xyz
Sign up to request clarification or add additional context in comments.

1 Comment

How can I make the object name variable as well? I tried: f.write('\n'.join(["{}.{} = '{}'".format(objname.name, (k for k in objname.__dict__.keys()),(v for v in objname.__dict__.values()))]))
2

If you are looking for something simple, you can use this for your example above.

import sys
class Foo(object):
    bar = 'hello'
    baz = 'world'

f = Foo()
print "\n".join(("`%s.Name=%s %s.Value=%s`" % (f.__class__.__name__, name, f.__class__.__name__, getattr(f, name)) for name in dir(f) if not name.startswith("__")))

will give

`Foo.Name=bar Foo.Value=hello`
`Foo.Name=baz Foo.Value=world`

For more complex serialization you are better off using pickle

Comments

0

Use Pickle library for object serialization.

https://docs.python.org/2/library/pickle.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.