简体   繁体   中英

Write Python object attributes to txt file

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...

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

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

Use Pickle library for object serialization.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM