python でデータ読み込みのパターンいろいろ
python で文字列データの読み込みを行う際の保存形式の簡単な覚え書き.
txt ファイルの利用
- サンプルテキストの準備
tiger pumpkin seaweed
- open 関数でファイルを読み込む (リスト形式の取得)
with open("sample.txt", "r") as f: # get as list sample_list = f.readlines()
- open 関数で読み込む (文字列形式の取得)
with open("sample.txt", "r") as f: # get as string sample_text = f.read()
yaml の利用
- サンプル yaml ファイルの準備 (ブロック形式)
test: "apple" test_list: ["ringo", "apel"] test_dict: {"en": "apple", "id": "apel"}
- pyyaml というモジュールを用いる
pip install pyyaml
- 辞書形式で取得
with open("sample.yaml", "r") as f: test_yaml = yaml.safe_load(f) print(test_yaml) # {'test': 'apple', 'test_list': ['ringo', 'apel'], 'test_dict': {'en': 'apple', 'id': 'apel'}}
- リストや辞書形式が可能
json
- サンプルファイルの準備
{ "test": "apple", "jp": ["ringo", "mikan"] }
- yaml と同様に読み込み可能
with open("sample.json", "r") as f: sample_json = json.load(f) print(sample_json) # {'test': 'apple', 'jp': ['ringo', 'mikan']}
比較
- txt ファイルはリスト形式にするくらいしかデータ構造を選べなさそう
- yaml と json はネストされたリストや辞書型を使用できて便利
- 可読性的には yaml の方が高い
- json は広く使われているため汎用性的には json が良い?