Modify default separators in json.dump in python 2.7.1
Clash Royale CLAN TAG#URR8PPP
Modify default separators in json.dump in python 2.7.1
In a json.dump method (python 2.7.1) the output has the default separator as (',' and ': '). I want to remove the comma and the colon so that my outputs are simply separated by white space.
I also want to remove the opening and closing braces. Is there any particular attribute of separator or string formatting that allows me to do this or is there any other solution?
For example after applying
with open(foutput, 'a') as f1:
json.dump(newdict, f1,sort_keys=True,indent=4)
I am getting output as :
"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,
But I want the below type output instead of that:
0.671962000 -28.875564044
0.696699155 -28.876061125
0.721436310 -28.877760536
0.746173465 -28.883116087
0.770910620 -28.898838970
Please note I only want this in python.
Thanks in advance!
csv
1 Answer
1
You are not producing JSON, so don't use the JSON module. You are producing CSV data, with a space as delimiter. Use the csv
module, or use simple string formatting.
csv
Using the csv
module:
csv
import csv
with open(foutput, 'a', newline='') as f1:
writer = csv.writer(f1, delimiter=' ')
writer.writerows(sorted(newdict.items()))
or simply using string formatting:
with open(foutput, 'a') as f1:
for key, value in sorted(newdict.items()):
f1.write(' n'.format(key, value)
newline='' was getting an error stating TypeError: 'newline' is an invalid keyword argument for this function ; After removing the newline it worked properly. Thank you.
– Samudranil Roy
Jun 21 '17 at 12:04
@SamudranilRoy: I wrote the answer with the assumption you use Python 3. For Python 2, use
'ab'
as the mode for the csv
module. The CSV standard is specific about how line endings are used, and those options allow the module to control them tightly.– Martijn Pieters♦
Jun 21 '17 at 12:07
'ab'
csv
@SamudranilRoy: any reason you removed the 'accept' mark, anything missing you feel I should add?
– Martijn Pieters♦
Jul 8 '17 at 18:54
It was by mistake may be.. I have not done intensionally. Sorry for the inconvenience.
– Samudranil Roy
Jul 9 '17 at 21:31
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That's not JSON. You are producing CSV data, why not use the
csv
module instead?– Martijn Pieters♦
Jun 21 '17 at 10:28