python でデータ読み込みのパターンいろいろ

python で文字列データの読み込みを行う際の保存形式の簡単な覚え書き.

txt ファイルの利用

tiger
pumpkin
seaweed
        
with open("sample.txt", "r") as f:
    # get as list
    sample_list = f.readlines()
        
with open("sample.txt", "r") as f:
    # get as string
    sample_text = f.read()
        

yaml の利用

test: "apple"
test_list: ["ringo", "apel"]
test_dict: {"en": "apple", "id": "apel"}
        
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"]
}
        
with open("sample.json", "r") as f:
    sample_json = json.load(f)
print(sample_json) # {'test': 'apple', 'jp': ['ringo', 'mikan']}
        

比較