【问题标题】:Modify default separators in json.dump in python 2.7.1在 python 2.7.1 中修改 json.dump 中的默认分隔符
【发布时间】:2017-11-24 04:56:15
【问题描述】:

在 json.dump 方法 (python 2.7.1) 中,输出的默认分隔符为 (',' 和 ': ')。我想删除逗号和冒号,以便我的输出简单地用空格分隔。

我还想删除左大括号和右大括号。 separator 的任何特定属性或字符串格式是否允许我这样做,或者是否有任何其他解决方案?

例如申请后

使用 open(foutput, 'a') 作为 f1: json.dump(newdict, f1,sort_keys=True,indent=4)

我得到的输出是:

{
    "0.671962000": 51.61292129099999, 
    "0.696699155": 51.61242420999999, 
    "0.721436310": 51.610724798999996, 
    "0.746173465": 51.60536924799999, 
    "0.770910620": 51.58964636499999, 
    "0.795647775": 51.543248571999996, 
    "0.820384930": 51.381941735, 
}

但我想要以下类型的输出而不是那个:

0.671962000  -28.875564044
0.696699155  -28.876061125
0.721436310  -28.877760536
0.746173465  -28.883116087
0.770910620  -28.898838970

请注意,我只希望在 python 中使用它。 提前致谢!

【问题讨论】:

  • 那不是 JSON。您正在生成 CSV 数据,为什么不改用 csv 模块?

标签: python json python-2.7


【解决方案1】:

您没有生成 JSON,因此不要使用 JSON 模块。您正在生成 CSV 数据,并以空格作为分隔符。使用csv module,或使用简单的字符串格式。

使用csv 模块:

import csv

with open(foutput, 'a', newline='') as f1:
    writer = csv.writer(f1, delimiter=' ')
    writer.writerows(sorted(newdict.items()))

或简单地使用字符串格式:

with open(foutput, 'a') as f1:
    for key, value in sorted(newdict.items()):
        f1.write('{} {}\n'.format(key, value)

【讨论】:

  • newline='' 收到错误说明 TypeError: 'newline' is an invalid keyword argument for this function ;删除换行符后,它工作正常。谢谢。
  • @SamudranilRoy:我在假设您使用 Python 3 的情况下编写了答案。对于 Python 2,使用 'ab' 作为 csv 模块的模式。 CSV 标准具体说明了如何使用行尾,这些选项允许模块严格控制它们。
  • @SamudranilRoy:你删除“接受”标记的任何原因,你觉得我应该补充什么?
  • 这可能是错误的..我没有刻意这样做。很抱歉给您带来不便。
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2021-04-30
相关资源
最近更新 更多