将字典写入文本文件?

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

我不知道该怎么做,因为我在 python 还是个初学者。 如果有人知道如何解决这个问题,请提供答案。

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

首先,您正在以读取模式打开文件并尝试向其中写入内容。 咨询 - 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
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()

您的第一个代码块的问题是您以 'r' 打开文件,即使您想使用 'w'

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

我知道这是一个老问题,但我也想分享一个不涉及 json 的解决方案。我个人不太喜欢 json 因为它不允许轻松附加数据。 如果您的起点是字典,您可以先将其转换为数据框,然后将其附加到您的 txt 文件中:

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

我在 python 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))

对于列表理解爱好者,这将在 dog.txt

中的新行中写入所有 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))