How would you open this file?

Kent Johnson kent at kentsjohnson.com
Thu Feb 23 18:01:32 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

You need to assign the result of open_file() to a variable. The 
'filename' variable inside open_file() is not available outside the 
function:

filename = open_file()

By the way 'filename' is a pretty bad name, since it contains a file 
object, not a string. Maybe call it f instead. ('file' is also a bad 
name because it is the name of a Python built-in function.)

Kent



More information about the Python-list mailing list