Skip to content
Advertisement

write list of lists to file but each tuple has to be on a new line, using python

I have an ugly list of lists generated in a program, which looks like this:

 a= [[93.400000000000006, "high"], [98.600000000000009, 99.0, "high"], [121.30000000000001, 124.1000000000000]]

I am saving it to a text file as follows:

with open('sample.txt','a') as outfile:
    json.dump(a,outfile)
    outfile.write("nn")

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:

for i in range(len(a)):
    print a[i]

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:

a = [
        [93.400000000000006, "high"], 
        [98.600000000000009, 99.0, "high"], 
        [111.60000000000001, 112.5, "high"]
]

with open('sample.txt', 'a') as outfile:
    for sublist in a:
        outfile.write('{}n'.format(sublist))

The above code produces the output:

[93.400000000000006, 'high']
[98.600000000000009, 99.0, 'high']
[111.60000000000001, 112.5, 'high']
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement