Read list of lists of tuples in Python from file

夙愿已清 提交于 2019-12-25 08:49:59

问题


I'd like to read and write a list of lists of tuples from and to files.

g_faces = [[(3,2)(3,5)],[(2,4)(1,3)(1,3)],[(1,2),(3,4),(6,7)]]

I used

  • pickle.dump(g_faces, fp)
  • pickle.load(fp)

But the file is not human readable. Is there an easy way to do it?


回答1:


Try the json module.

import json

g_faces = [[(3,2), (3,5)],[(2,4), (1,3), (1,3)],[(1,2), (3,4), (6,7)]]

json.dump(g_faces, open('test.json', 'w'))

g_faces = json.load(open('test.json'))

# cast back to tuples
g_faces = [[tuple(l) for l in L] for L in g_faces]


来源:https://stackoverflow.com/questions/40074923/read-list-of-lists-of-tuples-in-python-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!