Closing a file before or after return?

Steve Purcell stephen_purcell at yahoo.com
Fri Feb 9 09:35:53 EST 2001


Gustaf Liljegren wrote:
> 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.

How about try/finally:

  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()

A neater way would just be:


  def user_exist(user):
    f = open('.htpasswd', 'r')
    found = 0
    for line in f.readlines():
      i = string.find(line, ':')
      if line[:i] == user:
        found = 1
        break
    return found


-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list