473,414 Members | 1,723 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

canonical file access pattern?

Recently, there was mentioned how someone who had understood Python's
error handling would write the "open and read file with error handling"
idiom. If I remember correctly, it went like this:

try:
f = file(filename, op)
except IOError, e:
# Handle exception
else:
# Use the file
f.close()

I don't think that's sufficient. First of all, opening a file is only
part of the job--reading and writing can go wrong too, and these are
not handled by the above code. Then I've seen OSError as well as IOError
raised occassionaly.

Seems like I have do this, then:

try:
f = file(filename, op)
except (OSError, IOError), e:
# Handle open() error
else:
try:
# read/write to the file
f.close() # flushes write buffers, so can fail, too
except (OSError, IOError), e:
# Handle read/write errors

Is it really so wrong, then, to fold the read/write operations and close()
into the first try suite and handle all those errors in one go?
I'd just like to have a definitive pattern that I can stick to that is
considered bullet-proof.

Hans-Joachim Widmaier
Jul 18 '05 #1
5 1526
Hans-Joachim Widmaier:
Then I've seen OSError as well as IOError raised occassionaly.
The documentation says only IOError can be raised. Is there a bug?

"When a file operation fails for an I/O-related reason, the exception
IOError is raised."
http://www.python.org/doc/current/li...e-objects.html
Seems like I have do this, then:

try:
f = file(filename, op)
except (OSError, IOError), e:
# Handle open() error
else:
try:
# read/write to the file
f.close() # flushes write buffers, so can fail, too
except (OSError, IOError), e:
# Handle read/write errors


This is not correct, since the file is not closed when an exception is
thrown by read or write.

If we assume the following:
1. A file that is opened should be closed in all cases
2. Every exception raised by read, write or close should be caught and
handled

Then this would need to be the algorithm:

try:
f = file("spam.txt", "w")
except IOError, e:
# Handle open() error
pass
else:
try:
try:
# read/write to the file
pass
except IOError, e:
# Handle read/write errors
pass
finally:
try:
f.close()
except IOError, e:
# Handle close error
pass

Not very pretty, but I can't think of a simplification that does not
violate one of the assumptions.

--
René Pijlman
Jul 18 '05 #2
Am Tue, 30 Dec 2003 12:00:52 +0100 schrieb Rene Pijlman:
The documentation says only IOError can be raised. Is there a bug?

"When a file operation fails for an I/O-related reason, the exception
IOError is raised."
Apart from the "usual suspects" like file does not exist or is write
protected, errors aren't that common, so you don't see them all the time.
Maybe my memory is failing, but I have this distinct recollection that I
once used a 'except IOError' and got a OSError, much to my surprise. But
then, this has been quite a while ago. Python was much younger
then, I was still a fledgling Pythonist, and maybe I attributed the
error to the wrong operation ...
This is not correct, since the file is not closed when an exception is
thrown by read or write.
Oh, sorry. I silently assumed this to be done in the exception handling
suite. Really should have made that explicit.
If we assume the following:
1. A file that is opened should be closed in all cases 2. Every
exception raised by read, write or close should be caught and handled

Then this would need to be the algorithm:

try:
f = file("spam.txt", "w")
except IOError, e:
# Handle open() error
pass
else:
try:
try:
# read/write to the file
pass
except IOError, e:
# Handle read/write errors
pass
finally:
try:
f.close()
except IOError, e:
# Handle close error
pass
While my first thought was: Why is the finally needed here? The close()
might just as well be the end of the else-suit. But it slowly dawns on me:
If there is another exception than IOError in the read/write suite,
closing of the file wouldn't take place.
Not very pretty, but I can't think of a simplification that does not
violate one of the assumptions.


Yes, I would second that. Alas, this means that the wonderful pattern

for line in file(filename, "r"):
process_line(line)

is unusable for any "production quality" program. ;-(
It certainly is ok for throw-away one-liners and (what I do often!)
interactive file converters.

Thanks for elaborating.

Hans-Joachim Widmaier
Jul 18 '05 #3
Hans-Joachim Widmaier <hj********@web.de> writes:
Am Tue, 30 Dec 2003 12:00:52 +0100 schrieb Rene Pijlman:

[...]
Then this would need to be the algorithm:

try:
f = file("spam.txt", "w")
except IOError, e:
# Handle open() error
pass
else:
try:
try:
# read/write to the file
pass
except IOError, e:
# Handle read/write errors
pass
finally:
try:
f.close()
except IOError, e:
# Handle close error
pass


While my first thought was: Why is the finally needed here? The close()
might just as well be the end of the else-suit. But it slowly dawns on me:
If there is another exception than IOError in the read/write suite,
closing of the file wouldn't take place.
Not very pretty, but I can't think of a simplification that does not
violate one of the assumptions.


Yes, I would second that. Alas, this means that the wonderful pattern

for line in file(filename, "r"):
process_line(line)

is unusable for any "production quality" program. ;-(

[...]

If that were true, why did exceptions get invented? If you don't need
to do something different in all those except: clauses, then don't put
them in. As you know, the nice thing about exceptions is that you're
allowed to handle them in sensible places, so typical usage is like
this:

def frob(filename):
f = file(filename, "w")
try:
# read/write to the file
finally:
f.close()

def blah():
try:
frob(filename)
except IOError, e:
# try something else, or
print e.strerror
or, even better:

def blah():
frob(filename)
Shock, horror, where's the except IOError:, you ask?! It's in the
calling function, of course.

Also, if you want to catch both OSError and IOError, note that
EnvironmentError is their common base class.
John
Jul 18 '05 #4
Am Wed, 31 Dec 2003 14:51:01 +0000 schrieb John J. Lee:

If that were true, why did exceptions get invented? If you don't need
to do something different in all those except: clauses, then don't put
them in.
One thing I need is to create an informative and useful error message
As you know, the nice thing about exceptions is that you're
allowed to handle them in sensible places, so typical usage is like
this:
[handling exceptions in the caller]
Shock, horror, where's the except IOError:, you ask?! It's in the
calling function, of course.
Hmm. The farther away from the actual point of error you catch it, the
harder it is to tell exactly what happened and to redo/work around it.
Also, if you want to catch both OSError and IOError, note that
EnvironmentError is their common base class.


Good tip! I didn't know that before.

Hans-Joachim Widmaier
Jul 18 '05 #5
Hans-Joachim Widmaier <hj********@web.de> writes:
Am Wed, 31 Dec 2003 14:51:01 +0000 schrieb John J. Lee: [...]
If that were true, why did exceptions get invented? If you don't need
to do something different in all those except: clauses, then don't put
them in.


One thing I need is to create an informative and useful error message


..strerror?

[...] Hmm. The farther away from the actual point of error you catch it, the
harder it is to tell exactly what happened and to redo/work around it.

[...]

So in some cases, you have fewer except statments, in others, more.
There's really no "canonical pattern" to it.
John
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: yaipa | last post by:
What would be the common sense way of finding a binary pattern in a ..bin file, say some 200 bytes, and replacing it with an updated pattern of the same length at the same offset? Also, the...
17
by: Douglas Alan | last post by:
Is there a canonical way of iterating over the lines of a file that are null-separated rather than newline-separated? Sure, I can implement my own iterator using read() and split(), etc., but...
7
by: Brian Sabolik | last post by:
I'm not sure if I've broken any Object Oriented rules or not, but ... I have projects in 2 different solutions that need to use each other's methods. Therefore I may have an "update" method in...
3
by: deko | last post by:
I have a (Access 2003) contact management database where the user can double-click a contact's phone number in a form and have the Windows Phone Dialer dial the number. The problem is the number...
1
by: Juan R. | last post by:
Introduction I am developing the CanonML language (version 1.0) as a way to generate, store, and publish canonical science documents on the Internet. This language will be the basis for the next...
1
by: Juan R. | last post by:
The initial CanonMath program presented here http://canonicalscience.blogspot.com/2006/02/choosing-notationsyntax-for-canonmath.html] was discussed with several specialists, including father of...
13
by: George | last post by:
Hi, I am re-writing part of my application using C#. This application starts another process which execute a "legacy" program. This legacy program writes to a log file and before it ends, it...
5
by: wpmccormick | last post by:
What is the cleanest way to gain access to object methods and properties across classes and files in the same namespace? Example: A form object frmForm in file frmForm.cs creates obj1 defined in...
2
by: JohnLorac | last post by:
Hello, I'm trying to load and write file on local disc drive using signed javascript file. But I have experienced problem running this url: ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.