LoginSignup
3
4

More than 5 years have passed since last update.

python3でファイルの中身をリスト変数に代入する方法

Posted at

テキストファイルの一覧をうまい感じでlist変数に入れて
Forループで処理とかできたらいいな。と思いやってみました。

単純にreadlines()をすると改行が入るので、
read().splitlines()でやるといい感じでした。

以下の2つのファイルを用意します。

list.txt
aaaa
bbbb
cccc
dddd
eeee
list.py
# -*- coding: utf-8 -*-

path_name='./list.txt'

with open(path_name, mode='r') as f:
    key_list1 = f.readlines()
with open(path_name, mode='r') as f:
    key_list2 = f.read().splitlines()


print("key_list1 : {}".format(key_list1))
print("key_list2 : {}".format(key_list2))

実行結果

ajitama@ajitama-ubu1810:~$ python list.py 
key_list1 : ['aaaa\n', 'bbbb\n', 'cccc\n', 'dddd\n', 'eeee\n']
key_list2 : ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee']

key_list2が望む結果となりました。
Python2でもPython3でも動作しました。

以前も悩んだので、メモしておきます。

3
4
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
3
4