1. TOP
  2. プログラム
  3. ソフト
  4. python
  5. テキストファイルの読み出し

テキストファイルの読み出し

read() readline() readlines()

引数なしでread()を呼び出せば,ファイル全体を一度に読み出すことが
できる。大きなファイルでこれを行うときには注意が必要だ。
1GBのファイルは1GBのメモリーを消費する。
fin = open('relativty', 'rt')
poem = fin.read()
fin.close()
len(poem)
150

字数の上限を指定すれば、read()が一度に返すデータの量を制限できる。
100文字ずつ読み、その後のチャンクを文字列のpoemに追加して元のデータ
を再現しよう
poem = ''
fin = open('relativty', 'rt')
chunk = 100
while True:
fragment = fin.read(chunk)
if not fragment:
break
poem += fragment

fin.close()
len(poem)
100

イテレータを使う

イテレータは一度に一行ずつ返す。
poem = ''
lines = open('relativty', 'rt')

for lines in fin:
poem += line
fin.close()
len(poem)
150