How would you open this file?

Larry Bates larry.bates at websafe.com
Thu Feb 23 19:04:06 EST 2006


Bob wrote:
> I want to open a file in a function and pass the file back to main so
> another function can manipulate the file, something like this:
> 
> # begin
> def open_file()
>   filename=open(options.filename_input,'r')
>   return filename
> 
> open_file()
> print filename.read()
> filename.close()
> # end
> 
> But this doesn't work... It appears that "open_file()" needs a
> variable, but in order to pass a variable to "open_file()" I first need
> a variable... but I would rather have the function send me "filename"
> without creating it main. Is that possible?
> 
> Is there a better way to have a function open a file and pass the file
> back to main than what I am trying to do?  Thanks!
> 

Your function returned filename but in the main program you didn't
have anywhere for it to be saved.

fp=open_file()
print fp.read()
fp.close()

Others have pointed out the filename is a bad choice for a
variable name as it is a pointer to a file object.  Most
tutorials and a lot of standard library code use fp.

-Larry Bates



More information about the Python-list mailing list