从文件中读取列表列表作为python中的列表列表 [英] Reading a list of lists from a file as list of lists in python

查看:73
本文介绍了从文件中读取列表列表作为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆