LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python question (https://www.linuxquestions.org/questions/programming-9/python-question-272701/)

gamehack 01-01-2005 06:19 PM

Python question
 
I've a little problem with my first python script... I've two files, one which has two functions and another one which I use for testing them. Here are the frunction:
Code:

def loaddb(file):
    """ loaddb function"""
    handle = open(file, "rb")
    info = pickle.loads(handle)
    return info

def writedb(tupple, file):
    """ writing the db """
    info = pickle.dumps(tupple)
    handle = open(file, "wb")
    result = handle.write(handle)

and my testing source file

Code:

from fileio import *
import pickle

record = ["name", "phone"]
writedb(record, "test.txt")

If I run my first file no exeptions are raised... but If I run the second one it gives this:
Code:

Traceback (most recent call last):
  File "scriptutils.py", line 307, in RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "debugger.py", line 595, in run
    exec cmd in globals, locals
  File "filestruct.py", line 5, in ?
    writedb(phone, "test.txt")
  File "fileio.py", line 9, in writedb
    info = pickle.dumps(tupple)
NameError: global name 'pickle' is not defined

The purpose of the writedb function is to pickle a tupple. If anyone could tell me where's the problem, it would be great.

Thanks very much

Dodgeram01 01-01-2005 08:10 PM

I believe you have to import pickle in your fileio.py file.

gamehack 01-02-2005 06:08 AM

It doesn't work also... :(

davholla 01-02-2005 08:26 AM

I maybe wrong but have you defined a pickle file somewhere eg
pickle_file = open(filename, "rb")
and in your first function the next line would be :-
info = Pickle.load(pickle_file)

BTW cPickle is quicker than pickle and works just as well. Here is an example from a program I wrote :-

def writedict(self, dictent):
#write dictionary to file
pickle_file = open(dictfile, "wb")
cPickle.dump(dictent, pickle_file)
pickle_file.close()

gamehack 01-02-2005 06:51 PM

Quote:

Originally posted by davholla
I maybe wrong but have you defined a pickle file somewhere eg
pickle_file = open(filename, "rb")
and in your first function the next line would be :-
info = Pickle.load(pickle_file)

BTW cPickle is quicker than pickle and works just as well. Here is an example from a program I wrote :-

def writedict(self, dictent):
#write dictionary to file
pickle_file = open(dictfile, "wb")
cPickle.dump(dictent, pickle_file)
pickle_file.close()

BTW why are you using self in the parameters list of the function? Just curious...

PS I fixed my problem

davholla 01-03-2005 05:21 AM

I used self as the function was part of a class.
How did you solve the problem ?


All times are GMT -5. The time now is 05:27 PM.