追加“导致追加”2次

2024-04-25 20:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试使用python脚本将给定的文本文件转换为.json文件。 我试图将双引号附加为:output_str = '"'+input_str+'"',但它会在输出中产生两次双引号。你知道吗

i.e. if input_str = row
output_str = ""row"" instead of "row"
row.append(str)
writer = csv.writer(open("data.json",'wb'), delimiter=',')
writer.write(row)

有什么建议吗?你知道吗


Tags: 文件ofcsv脚本jsoninputoutputif
3条回答

首先你的方法看起来不错。其次,我将使用json库来创建json文件:

import json
a = "this is a test"
json.dumps({"a": a})
>> '{"a": "this is a test"}'

你的方法实际上是正确的。Python可以在字符串本身周围加引号,因为它是string对象的表示。但是这些引号只是在控制台中显示字符串时添加的,否则它们就不存在了!你知道吗

>>> foo = "foobar"
>>> foo
'foobar'
^      ^
# quotes add via displayed by str() method of foo
>>> '"%s"' % foo
'"foobar"'

来自shell的一些代码示例会更好,但是您可能会在字符串引号周围看到shell引号。你知道吗

我建议使用json library将字典自动转换为json文件。它会帮你处理一切的。你知道吗

相关问题 更多 >