如何让python在将字符串写入文件时使用双引号

Vin*_*nod 3 python string file-io

我在 python 中有一个列表

L = [[u'2014-12-02', 727.75], [u'2014-12-01', 733.65]]
Run Code Online (Sandbox Code Playgroud)

要写入文本文件。

我希望文件包含

[["2014-12-02", 727.75], ["2014-12-01", 733.65]]
Run Code Online (Sandbox Code Playgroud)

如果我写 file.write(str(L))

[['2014-12-02', 727.75], ['2014-12-01', 733.65]]

将写入文件。

Pie*_*rre 5

由于预期输出是有效的 JSON,您可以尝试:

import json

L = [[u'2014-12-02', 727.75], [u'2014-12-01', 733.65]]
with open("outfile", "w") as fdesc:
    json.dump(L, fdesc)
Run Code Online (Sandbox Code Playgroud)

您可能想fdesc.write('\n')json.dump()通话后添加。