首页 > 解决方案 > 我如何将字典取出文件保存在 csv 文件中并将其存储为字典

问题描述

这是在我的 csv 文件中:

{'Name': 'The Hero', 'Min Damage': 2, 'Max Damage': 4, 'Defence': 1, 'HP': 20, 'Inventory': [], 'fought': False, 'Y': 1, 'X': 0}

这就是我试图把字典拿出来的东西

def resumegame():
    filename = 'C:/test/savegame.csv'
    if not os.path.isfile(filename):
        return {}
    with open(filename) as ifh:
        return dict(line.split() for line in ifh)

标签: pythondictionaryfile-io

解决方案


您可以使用yaml模块

import yaml

def resumegame():
    filename = 'C:/test/savegame.csv'
    if not os.path.isfile(filename):
        return {}
    with open(filename) as ifh:
        return yaml.load(ifh)

推荐阅读