Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7047683
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:48:03+00:00 2026-05-28T02:48:03+00:00

I got that the with statement help you to turn this: try: f =

  • 0

I got that the with statement help you to turn this:

try:
    f = open(my_file)
    do_stuff_that_fails()
except:
    pass
finally:
    f.close()

Into:

with open(my_file) as f:
    do_stuff_that_fails()

But how is that better? You still have to handle the case with the file not being able to be opened (like prompting the user to tell him he doesn’t have permissions), so in reality you’d have:

try:
    with open(my_file) as f:
        do_stuff_that_fails()
except (IOError, OSError, Failure) as e:
    do_stuff_when_it_doesnt_work()

Which is equivalent to:

try:
    f = open(my_file)
    do_stuff_that_fails()
except (IOError, OSError, Faillure) as e:
    do_stuff_when_it_doesnt_work()
finally:
    f.close()

Yes, you gained two lines, but you added a level of nesting which doesn’t make it easier to read. Is the purpose of the with statement to save you two lines or am I missing something?

It seems a lot to add a keyword just for that, so I feel like there is some syntax to handle the additional try/except that I don’t know about.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T02:48:04+00:00Added an answer on May 28, 2026 at 2:48 am

    For a start, it helps prevent the problem you’ve introduced in your try ... finally ... example.

    The way you’ve structured it, if an exception is thrown while trying to open the file then you will never bind an open file to the name f, leading to either a NameError in the finally clause (if f has never been bound within scope) or something entirely unexpected (if it has).

    The correct structure (equivalent to the with) is:

    f = open(my_file)
    
    try:
        do_stuff_that_fails()
    finally:
        f.close()
    

    (note – no need for an except clause if you’ve got nothing to do there).

    Your second example similarly is wrong, and should be structured like:

    try:
        f = open(my_file)
    
        try:
            do_stuff_that_fails()
        except EXPECTED_EXCEPTION_TYPES as e:
            do_stuff_when_it_doesnt_work()
        finally:
            f.close()
    
    except (IOError, OSError) as e:
        do_other_stuff_when_it_we_have_file_IO_problems()
    

    The second is (as stated in another answer) that you can’t forget to call f.close().

    BTW, the term is “context management”, not “resource management” – the with statement manages contexts, some of which may be resources, but others not. For example, it’s also used with decimal to establish a decimal context for a particular block of code.

    Finally (responding to your comment to the previous answer) you should never rely on refcount semantics for handling resources in Python. Jython, IronPython and PyPy all have non-refcount semantics, and there’s nothing preventing CPython from going the other way (though it’s highly unlikely for the immediate future). In a tight loop (e.g. os.walk) it is very very easy to run out of file handles if code relying on refcount semantics is run on a VM with different behaviour.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a SQL statement in SQL Server 2005 that looks something like this:
I need some help with a mySQL statement. I've got a mySQL table that
I got the problem that the if-statement doesn't work. After the first code line
I've got a choose statement that should be setting my variable but for some
I've got a managed c++ library that is crashing when a delete statement is
I am trying to put 2 columns into a website, I've got that to
Anyone can help me with this statement? I'm trying to get amount of beads
So I've been at this mode thing for a while, and got some help
I've got an array that looks like this, but much longer: Array ( [0]
I got some help with an email form, and I feel that I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.