PeterParker
PeterParker

Reputation: 31

How to read a file in python and save its content to a two dimensional array?

In python I need to read a txt file that consists a maze made of A (start point), B (end point), spaces (for no wall) and * (for wall). Here is a picture how it could look like:

*************
*A*  *    * *
* * * * * * *
*   *   * * *
* * * * **  *
*   *    * B*
*************

I need to create a function that reads this file and returns an two dimensional array (numpy library) that consists the content of the txt file (0 for a wall, 1 for a space, 2 for value A and 3 for value B). In the other part of the array should be the column. How am I doing this?

I got so far:

import numpy


def read_file:
    f = open("file.txt", "r")
    line = f.readline()
    array = numpy.zeros((line, line.split()), dtype=int)
    f.close()
    return array

With that I get an error: type error, object can not be interpreted as an integer.What am I doing wrong?

How do I realize this?

Upvotes: 0

Views: 146

Answers (1)

iamchoosinganame
iamchoosinganame

Reputation: 1120

You could use a dict. I haven't tested the following code, but I think this would work.

Edit: I realized that the numpy array was going to be a flat vector instead of 2 dimensional and I adjusted the code to address this problem.

def read_file(file):
    # dict storing replacements
    code = {'*':0,' ':1,'A':2,'B':3}
    f = open(file, "r")
    s = f.read()
    f.close()
    lines = s.split('\n')
    # get a list of lists with each character as a separate element
    maze = [list(line) for line in lines]
    # Get the dimensions of the maze
    ncol = len(maze[0])
    nrow = len(maze)
    # replace the characters in the file with the corresponding numbers
    maze = [code[col] for row in maze for col in row]
    # convert to numpy array with the correct dimensions
    maze = numpy.array(maze).reshape(nrow,ncol)
    return(maze)

Upvotes: 1

Related Questions