Home > Mobile >  How to write multiple lists into a text file where each list is written into a new line?
How to write multiple lists into a text file where each list is written into a new line?

Time:05-26

I have two python lists:

a_list = [1, 2, 3]
b_list = [4, 5, 6]

How can I do the following:

create new text file ---> convert lists to json string ---> write lists into the file (each list should have its own line in the file) ---> open the file ---> read each line into a new variable and convert back from json string to python list?

I am stuck here:

import json

a_list = [1, 2, 3]
b_list = [4, 5, 6]

with open('test.txt', 'w') as f:
    f.write(json.dumps(a_list))
    f.write(json.dumps(b_list))

(The json string is written on the same line.)

Thanks

CodePudding user response:

Using JSON

first you should put those lists into a dict

d = {
    "a" : a_list,
    "b" : b_list
}

Then you can dump it into .json file

json.dump(d,open("file.json","w"))

To read/load the files, you can use

d = json.load(open("file.json","r"))

which will return the original dictionary. ie,

{'a': [1, 2, 3], 'b': [4, 5, 6]}
  • Related