回答編集履歴

1

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

2017/03/21 07:57

投稿

can110
can110

スコア38266

test CHANGED
@@ -45,3 +45,61 @@
45
45
  ```
46
46
 
47
47
  というエラーが発生します。
48
+
49
+
50
+
51
+ 2017/03/21追記:`io.read()`が返す文字列の型について
52
+
53
+ --
54
+
55
+
56
+
57
+ [15.2. io — ストリームを扱うコアツール](http://docs.python.org/2.7/library/io.html)にて
58
+
59
+ > テキストモード (デフォルトか mode 引数に 't' が含まれている場合) では、ファイルの内容は unicode 文字列として返され、バイト列はプラットフォーム依存のエンコーディングか、 encoding が指定された場合は指定されたエンコーディングを使ってデコードされます。
60
+
61
+
62
+
63
+ と記載されているとおり、質問文のコードでは`io.open`時にエンコーディングを指定しているので、fin.read()で返される文字列は、内部で`utf-8`でデコードされた`unicode`型となります。
64
+
65
+ すなわちfin.read().decode('utf-8')する必要はありません。
66
+
67
+
68
+
69
+ 確認コード
70
+
71
+ ```
72
+
73
+ >python
74
+
75
+ Python 2.7.12 |Anaconda custom (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v
76
+
77
+ .1500 64 bit (AMD64)] on win32
78
+
79
+ Type "help", "copyright", "credits" or "license" for more information.
80
+
81
+ Anaconda is brought to you by Continuum Analytics.
82
+
83
+ Please check out: http://continuum.io/thanks and https://anaconda.org
84
+
85
+ >>> import io
86
+
87
+ >>> with io.open('data.csv',encoding='utf-8') as fin:
88
+
89
+ ... tmp = fin.read()
90
+
91
+ ...
92
+
93
+ >>> type(tmp)
94
+
95
+ <type 'unicode'>
96
+
97
+ >>> repr(tmp)
98
+
99
+ "u'a'"
100
+
101
+ ```
102
+
103
+
104
+
105
+