原文来源:https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file
我有一个字典,我打算把它写入一个文件。
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
第一个错误是因为:你要用read模式打开一个文件,尝试写入内容。这个需要查看python IO模块
第二个错误是因为:你只是将字符串写入文件。如果你想要写入字典对象,你要么需要将它转为string对象,要么将它转化为可序列化对象。
下面是Python3的写法:
import json
# as requested in comment
exDict = {'exDict': exDict}
with open('file.txt', 'w') as file:
file.write(json.dumps(exDict))
# 使用json.loads读取文本变为字典
In case of serialization
import cPickle as pickle
with open('file.txt', 'w') as file:
file.write(pickle.dumps(exDict))
# 使用pickle.loads读取文本变为字典
原文地址:https://www.cnblogs.com/everfight/p/write_dict_to_text.html
时间: 2024-11-02 19:11:03