Q on explicitly calling file.close

r rt8396 at gmail.com
Wed Sep 9 16:50:24 EDT 2009


On Sep 9, 3:18 pm, David C Ullrich <dullr... at sprynet.com> wrote:
(snip)
> These days I've actually got the syntax and spelling memorized -
> I can type "close()" without needing to look it up!

+1

You are so right David! I think some people around here need to look
up "code reuse". Here are a couple of simple templates for our friends
to study...

def read_file(fname, mode='rb'):
    '''open file and return contents'''
    try:
        f = open(fname, mode)
        s = f.read()
        return s
    except:
        return 0
    finally:
        f.close()

def write_file(fname, s, mode='wb'):
    '''open file, truncate, and write string'''
    try:
        f = open(fname, mode)
        f.write(s)
        return 1
    except:
        return 0
    finally:
        f.close()


>>> s = read_file(fname)
>>> if s:
...     s += 'morecrap'
>>> write_file(s)

#-- Extra Credit --#
Create an append_file() function that takes a <filename> and <string>
as args and appends to the file returning 1 on success, and 0 on
failure.

#-- Double Extra Creidit --#
Create a backup_file() function that takes <filename> as arg and
creates a copy of the file with the extension ".bak"...
>>> backup_file('C:\test.txt') -> 'C:\test.bak'


--
def get_enlightened():
  import webbrowser
  url = 'http://jjsenlightenments.blogspot.com/'
  webbrowser.open(url)




More information about the Python-list mailing list