从文件中读取列表列表作为python中的列表列表 [英] Reading a list of lists from a file as list of lists in python
问题描述
我以列表列表的形式收集数据并将数据写入文本文件.文本文件中的数据看起来像
[[123231,2345,888754],[223467,85645]]
我想将其读回并存储在程序的列表列表中.但是,当我从文件中执行read()
并尝试创建一个平面列表时,它将所有内容作为一个字符串并且解释完全改变了,并且我无法查询以python中的列表作为普通列表读取后得到的结果. /p>
有人可以帮助我读取文件并以与列表列表相同的格式存储吗?
谢谢!
这看起来像是有效的 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)
这篇关于从文件中读取列表列表作为python中的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!