想把一个字典类型的变量写入到文件中,并且保证字典的格式为看起来比较舒服的格式。
使用 python 版本 2.7.10
# encoding: utf-8
import json
def main():
a = {
'addr': '北京',
'type': 1,
'deleted': False,
'name': None,
}
dict = json.dumps(a, encoding='utf-8', ensure_ascii=False, indent=4)
with open('a.txt', 'a') as f:
f.write(dict)
if __name__ == '__main__':
main()
上面方法得到的结果
{
"deleted": false,
"type": 1,
"addr": "北京",
"name": null
}
怎样得到
{
"deleted": False,
"type": 1,
"addr": "北京",
"name": None
}
请问怎么得到这种格式的文件?
还试过另外一种方法如下:
def main():
a = {
'addr': '北京',
'type': 1,
'deleted': False,
'name': None,
}
with open('a.txt', 'a') as f:
f.write('a = ' + str(a))
结果如下:
a = {'deleted': False, 'type': 1, 'addr': '\xe5\x8c\x97\xe4\xba\xac', 'name': None}
它没有格式化输出结果,而且 unicode 字符串是\u 形式转义了的,可读性很差,请问有什么办法可以改进?
使用 python 版本 2.7.10
# encoding: utf-8
import json
def main():
a = {
'addr': '北京',
'type': 1,
'deleted': False,
'name': None,
}
dict = json.dumps(a, encoding='utf-8', ensure_ascii=False, indent=4)
with open('a.txt', 'a') as f:
f.write(dict)
if __name__ == '__main__':
main()
上面方法得到的结果
{
"deleted": false,
"type": 1,
"addr": "北京",
"name": null
}
怎样得到
{
"deleted": False,
"type": 1,
"addr": "北京",
"name": None
}
请问怎么得到这种格式的文件?
还试过另外一种方法如下:
def main():
a = {
'addr': '北京',
'type': 1,
'deleted': False,
'name': None,
}
with open('a.txt', 'a') as f:
f.write('a = ' + str(a))
结果如下:
a = {'deleted': False, 'type': 1, 'addr': '\xe5\x8c\x97\xe4\xba\xac', 'name': None}
它没有格式化输出结果,而且 unicode 字符串是\u 形式转义了的,可读性很差,请问有什么办法可以改进?