newbie question:
Kevin Digweed
Kevin.Digweed at dial.pipex.com
Tue Aug 8 09:33:49 EDT 2000
Azratax wrote:
>
> i have made a simple module with a function (init() ) that opens a file
> to an object. I imported this module and ran init() . Thought i get no error,
> the fileobject is nowhere to be found. i have tried a dir() through every
> module yet cant find any object with that name... what have i done wrong?
> the code is (code in c:\python16\azrand\itemgen.py):
>
> import whrandom
> import pickle
> import string
> def init():
> mainlist = open('lists/main.txt')
The problem is that 'mainlist' is a variable local to the 'init()'
function. When 'init' returns,
'mainlist' is 'forgotten' and hence the file object it references will
be closed.
If you changed the function to:
def init():
global mainlist
mainlist = open('lists/main.txt')
... then the following will work:
import itemgen
itemgen.init()
print itemgen.mainlist
This is because by calling 'mainlist' global, it remains (in the
module's namespace) after init has returned and thus the file is not
closed.
Cheers, Kev.
More information about the Python-list
mailing list