0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルI/O由来でUnicodeDecodeErrorが出た時の対処法

Posted at

Background

VPSサーバでテキストかjsonを読み込んだ時にUnicodeDecodeErrorとエラーが出ました。 その時の対処方法をまとめます。

Method

ファイルを開いた時にencoding='utf-8'とパラメータを指定する。


import json

dict = {}
with open("sample.txt", encoding='utf-8') as fin:
    dict = json.load(fin)
print(dict)

で、エラーが出なくなりました。

公式ページ[python documentation 組み込み関数(open)]
(https://docs.python.org/ja/3.6/library/functions.html#open)でFunctionを調べてみると、

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

となっていて、パラメータがたくさんあります:anguished:
open はよく使うので各パラメータの意味を知っておくと良いかもです。

Reference

json.load() function give strange 'UnicodeDecodeError: 'ascii' codec can't decode' error
python documentation 組み込み関数(open)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?