teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

io\.read\(\)が返す文字列の型について追記

2017/03/21 07:57

投稿

8524ba23
8524ba23

スコア38352

answer CHANGED
@@ -21,4 +21,32 @@
21
21
  ```
22
22
  UnicodeEncodeError: 'cp932' codec can't encode character u'\u33a5' in position 18: illegal multibyte sequence
23
23
  ```
24
- というエラーが発生します。
24
+ というエラーが発生します。
25
+
26
+ 2017/03/21追記:`io.read()`が返す文字列の型について
27
+ --
28
+
29
+ [15.2. io — ストリームを扱うコアツール](http://docs.python.org/2.7/library/io.html)にて
30
+ > テキストモード (デフォルトか mode 引数に 't' が含まれている場合) では、ファイルの内容は unicode 文字列として返され、バイト列はプラットフォーム依存のエンコーディングか、 encoding が指定された場合は指定されたエンコーディングを使ってデコードされます。
31
+
32
+ と記載されているとおり、質問文のコードでは`io.open`時にエンコーディングを指定しているので、fin.read()で返される文字列は、内部で`utf-8`でデコードされた`unicode`型となります。
33
+ すなわちfin.read().decode('utf-8')する必要はありません。
34
+
35
+ 確認コード
36
+ ```
37
+ >python
38
+ Python 2.7.12 |Anaconda custom (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v
39
+ .1500 64 bit (AMD64)] on win32
40
+ Type "help", "copyright", "credits" or "license" for more information.
41
+ Anaconda is brought to you by Continuum Analytics.
42
+ Please check out: http://continuum.io/thanks and https://anaconda.org
43
+ >>> import io
44
+ >>> with io.open('data.csv',encoding='utf-8') as fin:
45
+ ... tmp = fin.read()
46
+ ...
47
+ >>> type(tmp)
48
+ <type 'unicode'>
49
+ >>> repr(tmp)
50
+ "u'a'"
51
+ ```
52
+