打开文件并创建2D数组

时间:2017-03-16 19:51:54

标签: python python-3.x file text-files

我有文件mapData.txt,其中包含多个数组:

[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

如何打开此文件,并使用这些行创建2D数组? 例如,在创建2D数组(称为" worldMap")后,如果我输入:

print(worldMap[0][0])

会打印1

3 个答案:

答案 0 :(得分:1)

您应该添加错误处理代码,但这似乎至少适用于您的示例:

INCLUDES="C:\Program Files\Microsoft Visual Studio 9.0\VC\ce\atlmfc\include"

答案 1 :(得分:1)

作为一种简单而有效的方法,您只需使用<body>

numpy.genfromtxt

答案 2 :(得分:0)

您可以使用ast.literal_eval评估文件中的每一行,或者按照以下方式自行解析:

>>> def parse_line(line):
...     return line.strip('\n[]').split(',')
...
>>> with open('myfile.txt') as f:
...     world_map = [list(map(int,parse_line(line))) for line in f]
...
>>> pprint(world_map)
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
>>>

但您应该考虑使用现有的文本序列化格式,例如json。所以,例如:

>>> my_list = [[1, 2, 3], [4, 5, 6]]
>>> import json
>>> with open('my_list.json', 'w') as f:
...     json.dump(my_list, json)
...

因此,上面将json文件写入磁盘。现在,从磁盘加载:

>>> with open('my_list.json') as f:
...     list2 = json.load(f)
...
>>> list2
[[1, 2, 3], [4, 5, 6]]
>>>