[Pythonmac-SIG] Re-opening files?

Just van Rossum just@letterror.com
Tue, 7 Mar 2000 23:58:48 +0100


At 2:53 PM -0800 07-03-2000, Chris Barker wrote:
>I am having a problem (more of an annoyance actually) when I try to
>re-open a file that I am writing to. I get an erro when I do this:
>
>file = open('filename','wt')

Erm, what deos the 't' mean in the mode?

>file.write('some stuff\n')
>
>file = open('filename','wt')
>
>I get an " IOError: [Errno 22] INvalid agrument 'filename' "
>
>
>
>why would I want to do something as stupid as this? you might ask.
>
>Well, strickly speaking, I don't. The problem is that if I am running a
>script in the IDE, and it crashes after opening a file for writing, but
>before closing it, then when I go to run the script again, I get this
>erro. This requires me to go back, selct the file.close() line, run it,
>and then run the script again. Again, mostly an annoyance, but I seem to
>run into it A LOT.
>
>By the way, the above code works just fine on Linux. Python appears to
>just re-wind the file (probably just the output buffer), without erasing
>it. Curious behavior, but it works for me!

Hm, I don't know what the "official" behavior should be, but it doesn't
seem unreasonable to me that you get an exception when opening a file for
writing twice.

I run into the same thing myself quite often, but I find it only a minor
annoyance, and usually blame it on myself ;-) In case I get really annoyed,
I do this:

f = open(filename, "w")
try:
    ...stuff that might crash...
finally:
    f.close()

>While I'm at it, other IDE questions:
>
>Is there a way to get the output window in the IDE to be interactive? I
>often would like to use the command line after my script terminates to
>check something out, but there is no way to do this.

??? I don't follow. But: have a look at the little popupmenu at the top
right corner of the interactive window, it has an entry called "Namespace"
which offers a list of open source files. After slecting your
script/module, the interactive window is executing commands in *that*
namespace.

>Also, is there an easy way to change the working directory in the IDE
>interactive window? import os, os.chdir('the whole path') is kind of a
>pain.

There are two scripts in in the Scripts menu called "Insert file name" and
"Insert folder name". Seems fairly convenient...

Just