I could use some help making this Python code run faster using only Python code.

Python Maniac raychorn at hotmail.com
Thu Sep 20 17:59:48 EDT 2007


I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(line):
    s = ''
    for c in line:
        s += chr(ord(c) | 0x80)
    return s

def descrambleLine(line):
    s = ''
    for c in line:
        s += chr(ord(c) & 0x7f)
    return s

def scrambleFile(fname,action=1):
    if (path.exists(fname)):
        try:
            f = open(fname, "r")
            toks = fname.split('.')
            while (len(toks) > 2):
                toks.pop()
            fname = '.'.join(toks)
            if (action == 1):
                _fname = fname + '.scrambled'
            elif (action == 0):
                _fname = fname + '.descrambled'
            if (path.exists(_fname)):
                os.remove(_fname)
            ff = open(_fname, "w+")
            if (action == 1):
                for l in f:
                    ff.write(scrambleLine(l))
            elif (action == 0):
                for l in f:
                    ff.write(descrambleLine(l))
        except Exception, details:
            print 'ERROR :: (%s)' % details
        finally:
            f.close()
            ff.close()
    else:
        print 'WARNING :: Missing file "%s" - cannot continue.' % fname




More information about the Python-list mailing list