将字典写入文件只会产生键



在这个程序中,输出只显示键,但是我该怎么做才能使键和值都保存在data.txt文件

myfile = open(r'data.txt','w')
d = {'studentName':'ABC''n','RollNo':'2'}
myfile.writelines(d)
myfile.close()

序列化它的最好方法是使用JSON格式,内容如下,使用json.loads,您将能够反序列化字典中的结构

import json
d = {'studentName': 'ABC', 'RollNo': '2'}
with open(r'data.txt', 'w') as myfile:
myfile.write(json.dumps(d))
# outputs
{"studentName": "ABC", "RollNo": "2"}

对于自定义逐行格式,迭代并写入每个

d = {'studentName': 'ABC', 'RollNo': '2'}
with open(r'data.txt', 'w') as myfile:
for k, v in d.items():
myfile.write(f"{k}:{v}n")
# outputs
studentName:ABC
RollNo:2

try this

d = {'studentName': 'ABC''n', 'RollNo': '2'}
with open("data.txt", 'w') as f:
for key, value in d.items():
f.write('%s:%s' % (key, value))

会给

studentName:ABC
RollNo:2

d = {'studentName':'ABC', 'RollNo':'2'}
with open('data.txt', 'w') as f:
for key, value in d.items():
f.write(f'{key} : {value} n')

相关内容

  • 没有找到相关文章

最新更新