python怎么写⼊字典_python3.x-将字典写⼊⽂本⽂件?python 3.x-将字典写⼊⽂本⽂件?
我有⼀本字典,正在尝试将其写⼊⽂件。
exDict = {1:1, 2:2, 3:3}
with open('', 'r') as file:
file.write(exDict)
然后我有错误
file.write(exDict)
TypeError: must be str, not dict
所以我修复了这个错误,但是⼜出现了另⼀个错误
exDict = {111:111, 222:222}
with open('', 'r') as file:
file.write(str(exDict))
错误:
file.write(str(exDict))
io.UnsupportedOperation: not writable
我不知道该怎么做,因为我还是python的初学者。如果有⼈知道如何解决该问题,请提供答案。
注意:我使⽤的是python 3,⽽不是python 2
8个解决⽅案
93 votes
⾸先,您以读取模式打开⽂件并尝试将其写⼊。咨询-IO模式python
其次,您只能将字符串写⼊⽂件。 如果要编写字典对象,则需要将其转换为字符串或序列化。
import json
# as requested in comment
exDict = {'exDict': exDict}
with open('', 'w') as file:
file.write(json.dumps(exDict)) # use `json.loads` to do the reverse
在序列化的情况下
import cPickle as pickle
with open('', 'w') as file:
file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse
对于python 3.x pickle包导⼊将有所不同
import _pickle as pickle
hspandher answered 2019-11-08T10:19:29Z
22 votes
我在python 3:
with open('', 'w') as f:
print(mydictionary, file=f)
NKSHELL answered 2019-11-08T10:19:53Z
17 votes
fout = "/your/"
fo = open(fout, "w")
for k, v in yourDictionary.items():
fo.write(str(k) + ' >>> '+ str(v) + '\n\n')
fo.close()
Sange Negru answered 2019-11-08T10:20:10Z
10 votes
第⼀个代码块的问题是,即使您要使⽤'w'对其进⾏写操作,也要以“ r”打开⽂件
with open('/Users/your/path/foo','w') as data:
data.write(str(dictionary))
clyde_the_frog answered 2019-11-08T10:20:35Z
3 votes
如果您想要字典,则可以按名称从⽂件导⼊,并且还添加了排序合理的条⽬,并且包含要保留的字符串,您可以尝试以下操作:
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
Mark Matthews answered 2019-11-08T10:21:06Z
0 votes
我知道这是⼀个⽼问题,但我也想分享⼀个不涉及json的解决⽅案。 我个⼈不太喜欢json,因为它不允许轻易附加数据。如果您的起点是字典,则可以先将其转换为数据框,然后将其附加到txt⽂件中:
import pandas as pdpython怎么读文件夹下的文件夹
one_line_dict = exDict = {1:1, 2:2, 3:3}
df = pd.DataFrame.from_dict([one_line_dict])
<_csv('', header=False, index=True, mode='a')我希望这会有所帮助。
Angelo answered 2019-11-08T10:21:37Z
0 votes
您可以执⾏以下操作:
import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))
Shivam Verma answered 2019-11-08T10:22:09Z
-2 votes
import json
with open('tokenler.json', 'w') as file:
file.write(json.dumps(mydict, ensure_ascii=False)) malibayram91 answered 2019-11-08T10:22:26Z

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。