Home>

It is windows10.

If i enter the following and execute it, a garbled file will be generated.
The garbled characters will disappear except for the encoding = "utf-8" part.

Is the csv file not compatible with utf-8?

import csv
with open ("test.csv", "w", encoding = "utf-8", newline = "") as file:
    csv_file = csv.writer (file, delimiter = ",")
    csv_file.writerow ([ "Hello", "and", "Goodbye"])


] (0e46c568526706d154d8cb139bb3d5d8.png)

  • Answer # 1

    It seems that you can open UTF-8 CSV in Excel by doing the following.

    [Illustration] How to easily open UTF-8 CSV with just Excel (Excel for Office 365) --Qiita

    Postscript

    I confirmed that when BOM is attached, the characters are not garbled even if it is opened as it is.
    In Python, it seems that you can add a BOM with utf_8_sig as follows.

    Output UTF-8 with BOM CSV file in Python --Qiita

    However, it is the mainstream that UTF-8 does not have a BOM, and if it does, it may not be handled correctly when opened by another application. Be careful when using the output CSV in other than Excel.

  • Answer # 2

    Excel is read by shift_jis by default, so csv saved in utf-8 is garbled.

  • Answer # 3

    Is the csv file not compatible with utf-8?

    No.

    Excel doesn't support opening CSV files written in UTF-8 (without BOM) by double-clicking. If you open it with an application that supports UTF-8 (without BOM) (Python itself, a text editor, etc.), garbled characters will not occur.

    If you want to open a CSV file written in UTF-8 in Excel

    Add a BOM when creating. Double-click to open a CSV file without garbled characters.

    Instead of double-clicking to open it, open the Excel document (or create a new one) and then press the "From Text or CSV" button on the "Data" tab to use the PowerQuery editor. Encoding can be specified at the time of reading. CSV files can be read without garbled characters with or without BOM.

    Instead of double-clicking to open it (in older Excel), open the Excel document (or create a new one) and then press the Text File button on the Data tab to use the Text File Wizard. Encoding can be specified at the time of reading. CSV files can be read without garbled characters with or without BOM.

    There are methods such as.

  • Answer # 4

    Is the csv file not compatible with utf-8?

    That's not true. Check the character code of the garbled text file. Probably it is shift_jis. If you want to handle it with utf-8, open it with Notepad etc., specify the character code and save it.