def detect_encoding(csvfile):
    """ Since encoding detection is hard to get right (and work correctly
    every time), we limit ourselves here to UTF-8 or CP1252, whichever works
    first. CP1252 is basically the csv format you get if you use windows and
    excel and it is a superset of ISO-8859-1/LATIN1.

    """
    csvfile.seek(0)
    try:
        for line in csvfile.readlines():
            line.decode('utf-8')
        return 'utf-8'
    except UnicodeDecodeError:
        return 'cp1252'
