写字典到文本文件? [英] Writing a dictionary to a text file?

查看:93
本文介绍了写字典到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dictionary and am trying to write it to a 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

所以我解决了这个错误,但是又出现了另一个错误

So I fixed that error but another error came

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

错误:

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

我仍然不知道该怎么做,因为我还是python的初学者. 如果有人知道如何解决该问题,请提供答案.

I have no idea what to do as I am still a beginner at python. If anyone knows how to resolve the issue, please provide an answer.

注意:我使用的是python 3,而不是python 2

NOTE: I am using python 3, not python 2

推荐答案

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

First of all you are opening file in read mode and trying to write into it. Consult - IO modes python

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

Secondly, you can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

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泡菜包,导入会有所不同

For python 3.x pickle package import would be different

import _pickle as pickle

这篇关于写字典到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆