且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件中读取列表列表作为python中的列表列表

更新时间:2022-10-17 23:19:13

这看起来像是有效的 JSON .

所以您可以简单地做:

import json
with open(myfilename) as f:
    lst = json.load(f)

要将列表列表"存储在文件中,请执行

with open(myfilename, "w") as f:
    json.dump(lst, f)

I collected data in the form of list of lists and wrote the data into a text file. The data in the text file looks like

[[123231,2345,888754],[223467,85645]]

I want to read it back and store in a list of lists in my program. But when I do read() from the file and try creating a flat list then it takes everything as a string and the interpretation changes totally and i am not able to query the result I get after reading as normal list of lists in python.

Can someone help me with reading the file and storing in the same format as list of lists?

Thank you!

This looks like valid JSON.

So you can simply do:

import json
with open(myfilename) as f:
    lst = json.load(f)

To store your "list of lists" in a file, do

with open(myfilename, "w") as f:
    json.dump(lst, f)