【发布时间】:2020-08-27 07:11:15
【问题描述】:
请帮忙,我有一本字典,我需要将其写入 txt 文件,我需要更改 dic 的格式,以便在写入新文件时可以在下面获得所需的输出。谢谢!
我的听写:
sdata = {'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}
当前输出:
{'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}
如何将其保存为以下格式而不是上述格式的文件?
期望的输出:
A, 1 2 3 4
B, 128 118
C, 5 6 7
D, 1 3 4
以下是我的代码:
def saveAndExit(sdata, x, r):
outFileName = "updated.txt"
outfile = open(outFileName, "w")
print (f'Content of xxx after updated {x} was added to key{r}:')
print (f'Content of xxx after updated {x} was added to key{r}:',file=outfile)
print (sdata) # wrong format
print (sdata, file=outfile)
outfile.close()
【问题讨论】:
标签: python dictionary file-handling