UnicodeDecodeError when opening a CSV from Excel

CharlieHOP

open("data.csv") crashes with UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9. The file came from Excel.

11

Comments 5

Join the discussion

Already have an account? Log in

  1. OllieGrantreplies: 2

    Excel often saves CSV in a Windows code page instead of UTF-8. Try:

    open("data.csv", encoding="cp1252")

    or, if the file is "CSV UTF-8" from Excel:

    open("data.csv", encoding="utf-8-sig")

    utf-8-sig also removes the invisible BOM at the start, which otherwise ends up glued to your first column name.

    1
      1. LiamByte

        The BOM thing bit me for ages. My first column was called "date" and I couldn't understand why row["date"] failed.

        0
      2. AmeliaRuns

        Best long-term fix: in Excel choose "CSV UTF-8" when saving. Then always use utf-8-sig in Python.

        4
        1. PiotrZ

          Always pass encoding= explicitly. The default depends on your operating system, so code that works on a Mac fails on Windows.

          4