Closing a file before or after return?

Quinn Dunkan quinn at lira.ugcs.caltech.edu
Sun Feb 11 18:53:26 EST 2001


On Fri, 9 Feb 2001 14:58:39 +0100, Gustaf Liljegren <gustafl at algonet.se> wrote:
>I'm using Python 2.0.
>
>Have a look at this function. It checks if a particular user (mail adress)
>exist in a .htpasswd file. The user name is what comes before ':' on each
>line.
>
># Check if user exists
>def user_exist(user):
>  f = open('.htpasswd', 'r')
>  for line in f.readlines():
>    i = string.find(line, ':')
>    if line[:i] == user:
>      return 1
>
>I'd like to close the file too, but I don't know where to put that
>statement. Of course, the file should be closed in both cases -- not just
>when the user is found.

# Check if user exists
def user_exist(user):
  f = open('.htpasswd', 'r')
  try:
      for line in f.readlines():
        i = string.find(line, ':')
        if line[:i] == user:
          return 1
  finally:
    f.close()

... will work.  But it's not necessary, since python will close the file for
you when the last reference disappears.  Explicitly deallocating anything more
complicated than memory or fds is usually good practice, though.



More information about the Python-list mailing list