Pickle Problem

tonyr1988 tonyr1988 at gmail.com
Thu Mar 15 13:24:02 EDT 2007


On Mar 15, 10:38 am, Gary Herron <gher... at islandtraining.com> wrote:
> tonyr1988 wrote:
> > I'm a complete python n00b writing my first program (or attempting to,
> > anyway). I'm trying to make the transition from Java, so if you could
> > help me, it would be greatly appreciated. Here's the code I'm stuck on
> > (It's very basic):
>
> > class DemoClass:
> >    def __init__(self):
> >            self.title = ["Hello", "Goodbye"]
>
> >    def WriteToFile(self, path = "test.txt"):
> >            fw = file(path, "w")
> >            pickle.dump(self.title, fw)
> >            fw.close()
>
> > if __name__=='__main__':
> >    x = DemoClass
> >    x.WriteToFile
>
> > It doesn't do any file I/O at all (that I see). I hope my syntax is
> > alright. If I just call WriteToFile, shouldn't it perform with the
> > default path? It gives me no errors and pretends to execute just fine.
>
> Several people have pointed out the problem, but when you get that
> fixed, I see another bit of trouble.   The pickle format is a binary
> format (be default), but you don't open the file in binary mode.   On
> Unix the distinction is (wisely) irrelevant, but on Windows you should
> open the file with a mode of "wb" not just "w".

Thanks guys for all the help. Sure enough, it was the parenthesis.
Most of my problems seem to be from under-simplifying (using
semicolons, brackets, etc) or, rarely, over-simplifying (forgetting
parenthesis). The biggest thing that was messing me up was the
mandatory "self" input. For some reason I was thinking that, if I had
parenthesis, I would have to define it. Fixing that works perfectly.

Also, about the binary format for opening files. The program that I'm
working on now is completely Linux-based - it's impossible for it to
work on any other OS. Should I still open with "wb" or not? Either
way, thanks for that tip!

One more (completely irrelevant) question. I don't quite understand
the double-underscore functions / methods / etc, such as __name__,
__main__, __init__. Is there a reason for the double-underscore? Does
it make anything special?

Again, thanks for the help...I'm probably going to ask a lot more of
it before too long. :)




More information about the Python-list mailing list