[Tutor] Creating files inside a script [I made a mistake!]
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Sun, 22 Apr 2001 23:48:57 -0700 (PDT)
On Sun, 22 Apr 2001, Sheila King wrote:
> :In retrospect, it makes sense why "r+" is one that raises IOError: it
> :means that we're assuming that the file exists and is good for reading and
> :writing. But like the regular "r" mode, if the file isn't there, then it
> :will raise an IOError.
>
> This is how I would have thought things work, and that is obviously what the
> docs say. But, then I just don't get why I was getting this error:
>
> File "gypsymail.py", line 117, in PrintErrorToLogFile
> logfile = open(logfilename, 'a+')
> IOError: (2, 'No such file or directory')
Very strange... It sounds like it might be something platform dependent,
because Python's open() is definitely using the C version of fopen() that
your system provides.
If you can tell us what kind of system you're on, we can verify that it's
a platform-specific issue. The Python docs hint as much when they talk
about how append might be wacky under certain Unices.
http://python.org/doc/current/lib/built-in-funcs.html
"... and 'a' opens it for appending (which on some Unix systems means that
all writes append to the end of the file, regardless of the current seek
position)."
Go figure.
> In any case, the script seems to be working fine, now. I changed that line of
> my program to
> logfile = open(logfilename, 'a')
>
> since I'm only going to write to the file, anyway, and I don't need
> the a+ functionality. It now seems to create the file, when the file
> doesn't already exist. Beats me, what the problem was before.
If we still want "a+" behavior, and have it do it nicely, we can write a
small wrapper function that does the same thing as open(), but test things
out:
###
def safe_aplus_open(filename):
"""A "permissive" style open() for mode "a+".
It appears that on some Unices, if the file doesn't exist,
we run into IOErrors. This function will try to open it
with "a+", and if it fails, creates the file, and tries again.
"""
try:
return open(filename, "a+")
except IOError:
open(filename, "w")
return open(filename, "a+")
###
I wonder if there's a better way to do this. Until then, if you need
"a+", this function should make things nicer.
By the way, have you been able to find a Python user's group in SoCal?
Just curious.
Good luck!