If I have a text file like this:
Hello World
How are you?
Bye World
How would I read it into a multidimensional array like this:
A good answer would be :
def read_text(path):
with open(path, 'r') as file:
line_array = file.read().splitlines()
cell_array = []
for line in line_array:
cell_array.append(line.split())
print(cell_array)
Which is optimized for readability.
But python syntax let's us use less code:
def read_text(path):
with open(path, 'r') as file:
line_array = file.read().splitlines()
cell_array = [line.split() for line in line_array]
print(cell_array)
And also python let's us do it only in one line!!
def read_text(path):
print([[item for item in line.split()] for line in open(path)])