I have an ugly list of lists generated in a program, which looks like this:
JavaScript
x
2
1
a= [[93.400000000000006, "high"], [98.600000000000009, 99.0, "high"], [121.30000000000001, 124.1000000000000]]
2
I am saving it to a text file as follows:
JavaScript
1
4
1
with open('sample.txt','a') as outfile:
2
json.dump(a,outfile)
3
outfile.write("nn")
4
When I open the text file, the values saved are an eyesore. How do I save each list to a new line?
For example if I wanted to print each list to a new line, I could simply do:
JavaScript
1
3
1
for i in range(len(a)):
2
print a[i]
3
thank you
EDIT: OUTPUT HAS TO LOOK LIKE :
[93.400000000000006, “high”]
[98.600000000000009, 99.0, “high”]
i.e each on one line.
Advertisement
Answer
I really don’t any reason here to use json.dumps
. You can just use a normal for
loop:
JavaScript
1
10
10
1
a = [
2
[93.400000000000006, "high"],
3
[98.600000000000009, 99.0, "high"],
4
[111.60000000000001, 112.5, "high"]
5
]
6
7
with open('sample.txt', 'a') as outfile:
8
for sublist in a:
9
outfile.write('{}n'.format(sublist))
10
The above code produces the output:
JavaScript
1
4
1
[93.400000000000006, 'high']
2
[98.600000000000009, 99.0, 'high']
3
[111.60000000000001, 112.5, 'high']
4