0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonで文字のリストをリストに変換したい

Posted at

こんなケース

data.txt
[
    "a",
    "b",
    "c"
]

このようなリスト形式のデータを持っているdata.txtがあります
このdata.txtを普通に読み込んでも、文字として扱われてしまいます
ここで、このテキストをlist型で取得するにはどうすれば良いでしょうか?

これでも一応出来るけど……

解法の一つとしてeval関数が使えます
しかし、皆さんご存知の通りこいつは任意コードが実行できてしまうので大変よろしくないです

個人的最適解

恐らく安全な方法はjson.loadを使うことです
json形式のデータではありませんが、なんと対応してくれるんですね

import json

with open("data.txt", "r") as f:
    data = json.load(f)

print(type(data)) # -> <class 'list'>
print(data[0]) # -> a
print(data[1]) # -> b
print(data[2]) # -> c
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?