with statements and exceptions
John Salerno
johnjsal at NOSPAMgmail.com
Wed Oct 25 15:40:56 EDT 2006
John Salerno wrote:
> I'm thinking about using a with statement for opening a file, instead of
> the usual try/except block, but I don't understand where you handle an
> exception if the file doesn't open. For example:
>
> with open('myfile', 'r'):
> BLOCK
>
> I assume that BLOCK can/will contain all the other stuff you want to do,
> which may involve try/except blocks, but what if the initial open() call
> fails (for lack of file, etc.)? Is this the purpose of the with
> statement, to handle this itself? Is there still some way that I can
> respond to this and show the user an error message?
>
> Thanks.
Let me just toss this in as well:
def create_sql_script(self):
with open('labtables.sql') as sql_script:
return sql_script.read()
Does the file still get closed even though I have a return statement
inside the with block?
Thanks.
More information about the Python-list
mailing list