1

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!

1 Answer 1

1
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]]
Sign up to request clarification or add additional context in comments.

1 Comment

I need to have it so the code itself reads the file, sorry if i was not clear on that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.