【问题标题】:How to make python use double quotes while writing a string to a file如何在将字符串写入文件时使python使用双引号
【发布时间】:2014-12-02 14:59:51
【问题描述】:

我在 python 中有一个列表

L = [[u'2014-12-02', 727.75], [u'2014-12-01', 733.65]]

写入文本文件。

我希望文件包含

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

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

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

将被写入文件。

【问题讨论】:

  • 你为什么想让它看起来像那样?如果需要 JSON,请使用 json.dump 写入文件。
  • 无论如何试一试 - file.write(str(L)).replace("'", '"')
  • @NedBatchelder 你说得对,我想写入一个 json 文件。
  • 嘿,我的评论具有误导性(仅在您的特定示例中有用),@Pierre 发布了正确的方法

标签: python string file-io


【解决方案1】:

由于预期的输出是有效的 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)

您可能想在json.dump() 调用之后添加fdesc.write('\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2011-04-08
    • 1970-01-01
    • 2012-09-02
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多