Pythonでテキストファイルを読み込む

プレーンなテキストファイルをwith構文で読み込む時に試したメモです。
以前挑戦したCSVモジュールを利用してのTSVファイルを読み込む方法はこちら

Windowsコマンドプロンプト上で動かしたため、出力に用意したテキストファイルはShift_JISとしています。

あ
い
う
え
お

目次

1行ずつ読み込む iterator

# -*- coding: utf-8 -*-
from __future__ import print_function

with open('sjis.txt') as f:
    for line in f:
        print(line, end='')
  • Python 2.7 での実行結果
あ
い
う
え
お
  • Python 3.5 での実行結果
あ
い
う
え
お

特別な理由が無ければiteratorを利用して1行ずつ読み込む方法で十分なようですが、iteratorを利用しない方が良い場合もあるようです。

全部読み込む read()

# -*- coding: utf-8 -*-
from __future__ import print_function

with open('sjis.txt') as f:
    print(f.read(), end='')
  • Python 2.7 での実行結果
あ
い
う
え
お
  • Python 3.5 での実行結果
あ
い
う
え
お

数GBにもおよぶログファイルなどはメモリが足りなくなりそうです。

リストとして全部読み込む readlines()

# -*- coding: utf-8 -*-
from __future__ import print_function

with open('sjis.txt') as f:
    print(f.readlines())
  • Python 2.7 での実行結果
['\x82\xa0\n', '\x82\xa2\n', '\x82\xa4\n', '\x82\xa6\n', '\x82\xa8\n']
  • Python 3.5 での実行結果
['あ\n', 'い\n', 'う\n', 'え\n', 'お\n']

1行だけ読み込む readline()

# -*- coding: utf-8 -*-
from __future__ import print_function

with open('sjis.txt') as f:
    print(f.readline(), end='')
  • Python 2.7 での実行結果
  • Python 3.5 での実行結果

いずれの方法も末尾の改行コードまで含まれています。
末尾の改行コードが不要な場合はrstrip()で除去などを行う必要があります。