将字典写入文本文件?

我有一本字典,正在试着把它写到一个文件里。

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

我如何解决这个问题?

355750 次浏览

首先,您在读模式下打开文件并尝试向其中写入。 请参考-< a href = “ https://docs.python.org/2/lessons/inputoutput.html”rel = “ nofollow norefrer”> IO mode 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
fout = "/your/outfile/here.txt"
fo = open(fout, "w")


for k, v in yourDictionary.items():
fo.write(str(k) + ' >>> '+ str(v) + '\n\n')


fo.close()

第一个代码块的问题在于,即使希望使用 'w'写入文件,也要以“ r”打开该文件

with open('/Users/your/path/foo','w') as data:
data.write(str(dictionary))

我知道这是个老问题,但我还是想分享一个不涉及 Json 的解决方案。我个人不太喜欢 json,因为它不允许轻松地附加数据。 如果你的起点是一个字典,你可以首先把它转换成一个数据框架,然后把它附加到你的文本文件:

import pandas as pd
one_line_dict = exDict = {1:1, 2:2, 3:3}
df = pd.DataFrame.from_dict([one_line_dict])
df.to_csv('file.txt', header=False, index=True, mode='a')

希望这个能帮上忙。

你可以这样做:

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

Https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

如果你想要一个字典,你可以从一个文件导入名称,并添加条目,很好地排序,并包含字符串,你想要保留,你可以尝试这样做:

data = {'A': 'a', 'B': 'b', }


with open('file.py','w') as file:
file.write("dictionary_name = { \n")
for k in sorted (data.keys()):
file.write("'%s':'%s', \n" % (k, data[k]))
file.write("}")

然后输入:

from file import dictionary_name

我在巨蟒3中是这样做的:

with open('myfile.txt', 'w') as f:
print(mydictionary, file=f)
import json


with open('tokenler.json', 'w') as file:
file.write(json.dumps(mydict, ensure_ascii=False))

对于列表内涵爱好者来说,这将把所有的 key : value对写成新的一行

my_dict = {'foo': [1,2], 'bar':[3,4]}


# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]


# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
[ my_file.write(f'{st}\n') for st in list_of_strings ]
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
file.write(str(exDict))

在我的例子中,我必须以 YAML 格式在文件中编写字典。我发现这个问题很有帮助,但是答案只有 JSON 或 String。因此,我在这里增加了我的探索-以便它可以帮助其他人的 YAML 格式。

import yaml


my_dictionary = {
"numbers": ["one", "two", "three"],
"colours": ["blue", "pink"],
"name": "Santosh"
}


with open("test.yaml", "w") as file:
file.write(yaml.dump(my_dictionary))

Yaml 文件中的输出为,

colours:
- blue
- pink
name: Santosh
numbers:
- one
- two
- three

希望这个能帮上忙!