[Tutor] Closing and Open File--TkFileDialogs

Kent Johnson kent37 at tds.net
Sat Feb 7 13:51:03 CET 2009


On Fri, Feb 6, 2009 at 9:59 PM, Wayne Watson
<sierra_mtnview at sbcglobal.net> wrote:
> Yes, I probably confused the two. The link you mentioned is the one I found
> most helpful of the ones I mentioned. Note that his descriptions here, like
> others, and to me at least, are minimal.

I think, as Alan says, there just is not much to say, and that you are
missing, or misinterpreting, what is there. Are you familiar with
basic file operations in Python (open, read, write)?

> First,
>
>   60   def asksaveasfile(self):
>   61
>   62     """Returns an opened file in write mode."""
>   63
>   64     return tkFileDialog.asksaveasfile(mode='w', **self.file_opt)
>
> Although, his description in the table doesn't mention the return type, it
> would seem like it should be the file name. However, the comment says the
> file is open. OK, how do you write on it?  Where's the object? OK, I see you
> say it is an object. I'm sure you're right, but how do you know?

When you call
f = open('myfile.txt', 'w')
the returned value is a file object representing an opened file in
write mode. You write to it by calling the write() method:
f.write('some text')

The value returned from asksaveasfile() is the same - an object
representing an opened file.
>
> BTW, I printed out the return from line 64 and got:
>  <open file 'C:/myfile.txt', mode 'w' at 0x0519D4A0>
>
> I may be misinterpreting this, but I took it as a file name, while it really
> may be the representation for an object.

Yes, it is the representation of a file object.  Many objects are
represented similarly if they don't have a reasonable literal
representation.

> Next consider:
>
>   66   def asksaveasfilename(self):
>   67
>   68     """Returns an opened file in write mode.
>   69     This time the dialog just returns a filename and the file is opened
> by your own code.
>   70     """
>   71
>   72     # get filename
>   73     filename = tkFileDialog.asksaveasfilename(**self.file_opt)
>   74
>   75     # open file on your own
>   76     if filename:
>   77       return open(filename, 'w')
>
> Here, the file is not opened, and one is on their own. So
> output=open(filename,'w') will open it for writing. No difficulty here.

Yes, and notice that the description of the returned object is
identical to that for asksaveasfile().

Kent


More information about the Tutor mailing list