回答編集履歴

1

python 2.7環境について追記

2017/11/11 18:47

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -1,6 +1,64 @@
1
+ 申し訳ないです、**python 2.7環境**というのを見落としてました。
2
+
1
3
  メモ帳でテキストファイルを保存しませんでしたかー?
2
4
 
3
5
  [バイトオーダーマーク](https://ja.wikipedia.org/wiki/%E3%83%90%E3%82%A4%E3%83%88%E3%82%AA%E3%83%BC%E3%83%80%E3%83%BC%E3%83%9E%E3%83%BC%E3%82%AF)略称 BOMが保存されていると思います。
6
+
7
+
8
+
9
+ python 2.7環境の場合は[codecs](https://docs.python.jp/2.7/library/codecs.html)を使う必要があります。
10
+
11
+ ```python
12
+
13
+ # -*- coding: utf-8 -*-
14
+
15
+ from __future__ import unicode_literals
16
+
17
+ import codecs
18
+
19
+
20
+
21
+
22
+
23
+ def main():
24
+
25
+ with codecs.open('test.txt', 'r', encoding='utf-8-sig') as f:
26
+
27
+ for text in f.readlines():
28
+
29
+ text = text.rstrip('\r\n')
30
+
31
+ print text, len(text)
32
+
33
+
34
+
35
+
36
+
37
+ if __name__ == '__main__':
38
+
39
+ main()
40
+
41
+
42
+
43
+ ```
44
+
45
+ > 消し方も教えてください。
46
+
47
+
48
+
49
+ 0. テキストファイルを保存する時にメモ帳以外のソフト(Bracketsなど)で保存する。
50
+
51
+ 0. バイナリエディタでBOMを削除。
52
+
53
+
54
+
55
+ プログラム側での対応としてファイルを読み込む時にエンコーディングをutf-8-sigで読み込み(回答文の方法)
56
+
57
+
58
+
59
+ ---
60
+
61
+ 以下はpython 3環境用の回答です。
4
62
 
5
63
  > f = open('test.txt', 'r')
6
64