29
16

More than 1 year has passed since last update.

Pythonでファイルを一行ずつ読み込む

Last updated at Posted at 2020-04-21

すごく基本的なことなんだけど、pythonであるテキストファイルを一行ずつ読み込む方法を調べてみた。

一番スマートだと感じた方法

with open('./test.txt') as f:
    for line in f:
       print line

他にも色々あるけど

多分上記のが一番スマートかな。
read(), readline(), readlines()などを使うサンプルをいくつもみたけど、一行ずつ処理するならば使う必要ない気がした。

read()を使う
with open('./test.txt') as f:
    lines = f.read()
    for l in lines.split("\n"):
        print(l)
readline()を使う
with open('./test.txt') as f:
    line = f.readline()
    while line:
        print(line.rstrip("\n"))
        line = f.readline()
readlines()を使う
with open('./test.txt') as f:
    lines = f.readlines()
    for l in lines:
        print(l.rstrip("\n"))

pythonはやりたい事に対して解決方法がたくさんありすぎるので、どれが良いか考えている時間が無意味に長くなってしまうのが良くないな。。

29
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
16