Pickle Problem

Larry Bates lbates at websafe.com
Thu Mar 15 11:30:20 EDT 2007


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.
> 
Just a couple of "issues" that can be fixed as follows:

import pickle

class DemoClass:
	def __init__(self):
		self.title = ["Hello", "Goodbye"]

	def WriteToFile(self, path):
		fw = file(path, "w")
		pickle.dump(self.title, fw)
		fw.close()

if __name__=='__main__':
    path='\\test.txt'
    x = DemoClass()
    x.WriteToFile(path)

Notes:

1) You have to call (follow by parenthesis) DemoClass() to get an instance.
   What you got was a pointer (x) to the DemoClass not an instance of
   DemoClass.

2) Same for WriteToFile()

3) Probably best to move the path to main and always pass it into
   WriteToFile.

-Larry



More information about the Python-list mailing list