a method to replace heroku login details in netrc file

def _update_netrc(self, netrc_path, auth_token, account_email):
        
        ''' a method to replace heroku login details in netrc file '''
    
    # define patterns
        import re
        record_end = '(\n\n|\n\w|$)'
        heroku_regex = re.compile('(machine\sapi\.heroku\.com.*?\nmachine\sgit\.heroku\.com.*?)%s' % record_end, re.S)
        
    # retrieve netrc text
        netrc_text = open(netrc_path).read().strip()
        
    # replace text with new password and login
        new_heroku = 'machine api.heroku.com\n  password %s\n  login %s\n' % (auth_token, account_email)
        new_heroku += 'machine git.heroku.com\n  password %s\n  login %s\n\n' % (auth_token, account_email)
        heroku_search = heroku_regex.findall(netrc_text)
        if heroku_search:
            if re.match('\n\w', heroku_search[0][1]):
                new_heroku = new_heroku[:-1]
                new_heroku += heroku_search[0][1]
            netrc_text = heroku_regex.sub(new_heroku, netrc_text)
        else:
            netrc_text += '\n\n' + new_heroku
        
    # save netrc
        with open(netrc_path, 'wt') as f:
            f.write(netrc_text)
            f.close()

        return netrc_text