Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使python在向文件写入字符串时使用双引号_Python_String_File Io - Fatal编程技术网

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

如何使python在向文件写入字符串时使用双引号,python,string,file-io,Python,String,File Io,我有一个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,您可以尝试: import json L =

我有一个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,您可以尝试:

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')

为什么要这样?如果您想要JSON,请使用
JSON.dump
来编写文件。无论如何,请尝试使用
file.write(str(L)).replace(“'”,“'”)
@nedbatcheld您是对的,我想写入JSON文件。嘿,我的评论有误导性(仅在您的特定示例中有用),正确的方法是@Pierre发布的