python - 将字典写入文本文件?

标签 python python-3.x dictionary file file-writing

我有一本字典,正在尝试将其写入文件。

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)

然后我遇到了错误

file.write(exDict)
TypeError: must be str, not dict

所以我修复了这个错误,但又出现了另一个错误

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))

错误:

file.write(str(exDict))
io.UnsupportedOperation: not writable

如何解决这个问题?

最佳答案

首先,您以读取模式打开文件并尝试写入其中。 咨询-IO modes python

其次,您只能将字符串或字节写入文件。如果要编写字典对象,则需要将其转换为字符串或序列化。

import json

# as requested in comment
exDict = {'exDict': exDict}

with open('file.txt', 'w') as file:
     file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

如果是序列化

import cPickle as pickle

with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

对于 python 3.x pickle 包导入会有所不同

import _pickle as pickle

关于python - 将字典写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965507/

相关文章:

python - 基本 Flask 应用程序未运行(类型错误 : required field "type_ignores" missing from Module)

python - 如果其中一个值在两个字典中都匹配,则用另一个字典值更新一个大字典的最快方法是什么?

python - 如何在 matplotlib/Python 中更改后端

python - 使用python3指定放置下载文件的路径

python - 如何将具有值为列表的列的数据框转换为数据框,其中该列中每个列表的每个元素都成为新行

python - 如何在没有模块的情况下格式化 csv 文件(例如省略第一行和第一列)?

python - 如何使 "ValueError"异常替换列表中的项目

python - importlib.reload 不会重新加载以编程方式生成的文件

算法:从邻接表到视觉 map

python - 检查一个字典的值是否是另一个字典的键