LoginSignup
48
24

More than 5 years have passed since last update.

python でファイルを read してリストにする時に、改行コードを入れない

Posted at

こんなファイルがあるとして

$ cat /tmp/foo.txt 
foo
bar

pon

readlines()を使うとこうなっちゃう

with open('/tmp/foo.txt', 'r') as f:
    lines = f.readlines()

    # print lines -> ['foo\n', 'bar\n', '\n', 'pon\n']

けど大抵の場合\nは付いてこなくて良いので、今まで何年もずっとこうやってた

with open('/tmp/foo.txt', 'r') as f:
    lines = map(lambda s: s.strip(), f.readlines())

    # print lines -> ['foo', 'bar', '', 'pon']

どうも素直に左から読めないし、map(strip, f.readlines())って書けないしですっきりしないので悶々としてた

けど、こう書けることをたまたま知って、とても感動したのでメモ

with open('/tmp/foo.txt', 'r') as f:
    lines = f.read().splitlines()

    # print lines -> ['foo', 'bar', '', 'pon']

これはすっきりしてて良いなぁ!
そんだけ!

48
24
2

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
48
24