Q:

Reading 2d array from file in Python

The following code fills a 2d array (grid) with random numbers(0 or 1): 
def create_initial_grid(rows, cols):

grid = []
for row in range(rows):
    grid_rows = []
    for col in range(cols):

        if random.randint(0, 7) == 0:
            grid_rows += [1]
        else:
            grid_rows += [0]

    grid += [grid_rows]
return grid

I want to fill the grid from a text file that looks like this:
7
0,0,0,0,0,0,0
0,0,1,0,1,0,0
0,0,1,1,1,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0

A:

Other option is to use numpy.loadtxt to read .txt (since you are use the array and matrix format):   
data = np.loadtxt("text.txt", delimiter=",",dtype=int , skiprows=1) 
print(data)

Out:
[[0 0 0 0 0 0 0]
 [0 0 1 0 1 0 0]
 [0 0 1 1 1 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]]

Note: 
skiprows=1 # parameter for skipping the first line when reading from
  the file.
dtype=int parameter for reading in the int format (default is
  float)

