You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个字典写入文件?代码仅写入Games_shop,求修改方案及理由

问题原因与修改方案

问题原因

你使用了文件打开模式'w'(写入模式),每次调用writing_to_file函数时,都会清空目标文件的原有内容,再写入当前传入的字典数据。因此先写入Fruit_shop的内容后,第二次调用写入Games_shop时会直接覆盖之前的内容,最终文件里只剩Games_shop的数据。

修改方案

方案1:使用追加模式'a'写入文件

将open函数中的'w'改为'a',同时可添加分隔线优化内容可读性:

def writing_to_file(shop) -> None:
    file_name = "something" + '.txt'
    # 替换为追加模式'a',不会清空原有内容
    with open('C:/Users/xyz/PycharmProjects/Shops/{0}'.format(file_name), 'a', encoding='utf-8') as f:
        for key, value in shop.items():
            f.write(key + '\n')
            for key1, value1 in value.items():
                f.write(f"{key1} : {value1}\n")
            f.write(f"{'}'}\n\n")  # 添加换行分隔不同店铺内容


Fruit_shop = {
    'Fruits {':{
        'A':'Apple',
        'B':'Ball'
    }
}
Games_shop = {
    'Games {':{
        'C':'Cricket',
        'F':'Football'
    }
}

writing_to_file(Fruit_shop)
writing_to_file(Games_shop)

理由:'a'是追加模式,打开文件后会将新内容追加到文件末尾,不会覆盖原有数据;添加encoding='utf-8'可避免潜在编码问题,换行分隔能让不同店铺的内容更清晰。

方案2:合并字典后一次性写入

如果不想多次打开文件,可先合并两个字典,再调用一次写入函数:

def writing_to_file(shop) -> None:
    file_name = "something" + '.txt'
    with open('C:/Users/xyz/PycharmProjects/Shops/{0}'.format(file_name), 'w', encoding='utf-8') as f:
        for key, value in shop.items():
            f.write(key + '\n')
            for key1, value1 in value.items():
                f.write(f"{key1} : {value1}\n")
            f.write(f"{'}'}\n\n")


Fruit_shop = {
    'Fruits {':{
        'A':'Apple',
        'B':'Ball'
    }
}
Games_shop = {
    'Games {':{
        'C':'Cricket',
        'F':'Football'
    }
}

# 合并两个字典
combined_shops = {**Fruit_shop, **Games_shop}
writing_to_file(combined_shops)

理由:一次性写入所有内容,仅调用一次'w'模式,既避免了文件被多次覆盖的问题,也减少了文件IO的开销。

方案3:为每个店铺生成独立文件

若需要分开保存不同店铺的数据,可修改函数让文件名包含店铺标识:

def writing_to_file(shop, shop_name) -> None:
    # 文件名加入店铺名称,避免互相覆盖
    file_name = f"{shop_name}.txt"
    with open('C:/Users/xyz/PycharmProjects/Shops/{0}'.format(file_name), 'w', encoding='utf-8') as f:
        for key, value in shop.items():
            f.write(key + '\n')
            for key1, value1 in value.items():
                f.write(f"{key1} : {value1}\n")
            f.write(f"{'}'}")


Fruit_shop = {
    'Fruits {':{
        'A':'Apple',
        'B':'Ball'
    }
}
Games_shop = {
    'Games {':{
        'C':'Cricket',
        'F':'Football'
    }
}

writing_to_file(Fruit_shop, "Fruit_shop")
writing_to_file(Games_shop, "Games_shop")

理由:每个店铺对应独立的文件,不会出现内容覆盖问题,方便单独查看和管理不同店铺的数据。

内容的提问来源于stack exchange,提问作者abhishekravoor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:39:24