Reputation: 31
I need to add line after line to a 2d array in python using numpy.
def read_file(file):
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols), dtype=int)
for line in lines:
maze = np.append(maze, line)
return maze
First I read a file and get the lines from that one. Then I am creating a 2d array using the count of lines and columns (-1 because of '\n' at the end). Then I want to append them to the array, but it looks really weird:
['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* * * * * * * * * B*\n'
'*****************************************************************\n']
['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* * * * * * * * * B*\n'
'*****************************************************************\n']
What am I doing wrong? Where is the error?
Expected output is a 2d array (17,65). Something like: [[0,0,0,0,0...0,0], [0,0,0,0...,0,0]...] etc.
I want to generate an array from this file:
*****************************************************************
*A * * * * * *
*** * ***** * ******* *** *** * *************** * *********** * *
* * * * * * * * * * * * * * *
* ******* * ******* ******* * * * ***** * * ******* * ***** *** *
* * * * * * * * * * * * * * * * *
* ***** * *** *********** * * * *** * * * * * *** *** *** ***** *
* * * * * * * * * * * * * * * * *
*** * * *** ***** ******* ******* *** ******* * * *** * * *** ***
* * * * * * * * * * * * * * * * * * *
* ***** ***** * *** * * *** * * * ***** *** * * *** * * *** *** *
* * * * * * * * * * * * * * * * * * *
* * ***** ***** * * * *** * ******* ********* * * * ***** * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *
* * * * * * * * * B*
*****************************************************************
every line is in brackets [] and after a new line a new bracket beginns.
Upvotes: 0
Views: 552
Reputation: 3047
If I get you right, you want to have all the integers in a numpy array padded with zeros. This is how I would do this.
# open and read file
file = open(data, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols),dtype=str)
for index,line in enumerate(lines):
for i in range(0,len(line)-1):
maze[index][i]= line[i]
return maze
this will produce this output:
[['*' '*' '*' ... '*' '*' '*']
['*' 'A' ' ' ... ' ' ' ' '*']
['*' '*' '*' ... '*' ' ' '*']
...
['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '']]
Upvotes: 1