0

This has been bugging me for a while. I can't find anything online that gives me an answer I am looking for. Hopefully you guys canshed some light on this:

Here is a piece of code:

class MyClass():
    def __init__(self):
        self.name = ''
        self.age = 0
        self.gender = ''


me = MyClass()
me.name = "john"
me.age = 23
me.gender = "male"

with open('MyFile', 'w') as f:
    dict = vars(me)
    for attr in dict:
        f.write(att + '\n')

Output:

name
age
gender

How i want the output to be like...

name: john
age: 23
gender: male

the format doesn't matter, but something where I can store an instance of a class in a file to be able to read from again.. Anyone have any ideas?

pypy
  • 160
  • 1
  • 8

3 Answers3

1

Pickle!

#save
file_handler = open("myfile.pkl", "w")
pickle.dump(me, file_handler)

#load
file_handler = open("myfile.pkl", "r")
me = pickle.load(file_handler)
katerinah
  • 111
  • 4
0

You could roll your own, or you could try pickle. This question has been answered before though.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
jgritty
  • 11,660
  • 3
  • 38
  • 60
  • can you please provide a link, I haven't been able to find anything online that solves this. Maybe I am wording my question wrong. – pypy Aug 14 '14 at 20:26
0

You should try pickle, but I think what you are looking for is just to make your code

with open('MyFile', 'w') as f:
    dict = vars(me)
    for attr in dict:
        f.write( attr + ': ' + str( dict[attr] ) + '\n') 
Romasz
  • 29,662
  • 13
  • 79
  • 154
nair.ashvin
  • 791
  • 3
  • 11
  • thank you yes that is was I am looking for, although I will try to go into pickle, because these things are going to be stored to be read from again. – pypy Aug 14 '14 at 20:28