简体   繁体   English

将字符串写入文件 python 时在文件内保留引号

[英]Keep quotation marks inside the file when writing string into a file python

I would like to write file with python我想用 python 写文件

My code is producing:我的代码正在生成:

{ date: 2018-11-28, weight: 172.91, height: 177.65, id:310 }

I want to have the following is the input inside the file我想要以下是文件内的输入

{ date: '2018-11-28', weight: 172.91, height: 177.65, id:310 }

With the single quote mark which I need it to be there.用单引号,我需要它在那里。

Any help please for writing string into file with single quote mark '.请帮助将字符串写入带有单引号的文件'。

my code:我的代码:

my_dict = { 'date': '2018-11-28', 'weight': 172.91, 'height': 177.65, 'id':310 }
my_dict = str(my_dict)
f = open('file.txt', 'w')
f.write(my_dict)
f.close()

Thanks谢谢

Use the JSON library.使用JSON库。 In your case you would use:在您的情况下,您将使用:

with open('file.txt', 'w') as f:
    json.dump(my_dict, f, indent=4)

Or, to mimic your approach to files:或者,模仿您处理文件的方法:

f = open('file.txt', w)
json.dump(my_dict, f, indent=4)
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM