Sadie
Sadie

Reputation: 11

Creating a 2D array from a one line txt file in Python

I'm attempting to read a one line text file into an array in python, but I am struggling with actually getting the file to transform into an 2D array. This is the text file:

6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0

The first number (6) represents the columns and the second number (4) represents the rows. Here is the code I have so far:

maze_1d_arr = open(sys.argv[1], 'r')

    maze = []

    maze_split = np.array([maze_1d_arr])

    size_X = len(maze_split)
    size_Y = len(maze_split[0])

    maze_grid = [int(x) for x in maze_split[2:]]

    maze = np.array(maze_grid).reshape(size_X, size_Y)

    start = np.where(maze_split == 2)
    end = np.where(maze_split == 3)

    path = astar(maze, start, end)
    print(path)

Sorry if this question has been asked before but I'm stumped at how to get it to work. Any help would be appreciated!

Upvotes: 1

Views: 120

Answers (1)

Lior Cohen
Lior Cohen

Reputation: 5755

import numpy as np

x = np.array([6, 4, 0, 0, 1, 0, 0, 0, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0])

print(x[2:].reshape(x[[1,0]]))

[[0 0 1 0 0 0]
 [2 0 1 0 1 1]
 [0 0 1 0 0 0]
 [0 0 0 0 3 0]]

Upvotes: 1

Related Questions