Help us understand the problem. What is going on with this article?

[Python] Excelで文字化けしないCSVファイルを書き出す

More than 1 year has passed since last update.

[Python] Excelで文字化けしないCSVファイルを書き出す

Byte Order Mark(BOM)をつければ、UTF-8のままExcelで開いても文字化けしないCSVを作ることが出来ます。
ファイルの出力の際に、encoding='utf_8_sigをつけるだけです。

with open ~を利用する場合

こちらの方の投稿を参照ください。

pandasを利用する場合

以下のようにencoding='utf-8-sig'を付与します。

import pandas as pd

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
df.to_csv('./df.csv', encoding='utf_8_sig')

もしBOMをつけ忘れてしまったら

以下のようにshellを叩けばBOM付きのファイルを作ることが出来ます。
こちらでも文字化けせずにExcelで開けるようになります。

cat <(printf "\xEF\xBB\xBF") without_bom.csv > with_bom.csv

without_bom.csvwith_bom.csvに当たる部分は必ず別の文字列を与えてください
もし同じ文字列与えてしまった場合、永遠に処理が終わりませんし、元々のファイルが壊れます
お気をつけください。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away