Question

Im trying to find a way to be able to input a matrix from a text file;

for example, a text file would contain

1 2 3
4 5 6
7 8 9

And it would make a matrix with those numbers and put it in matrix = [[1,2,3],[4,5,6],[7,8,9]]

And then this has to be compatible with the way I print the matrix:

 print('\n'.join([' '.join(map(str, row)) for row in matrix]))

So far,I tried this

chemin = input('entrez le chemin du fichier')

        path = input('enter file location') 

        f = open ( path , 'r')
        matrix = [ map(int,line.split(','))) for line in f if line.strip() != "" ]

All it does is return me a map object and return an error when I try to print the matrix.

What am I doing wrong? Matrix should contain the matrix read from the text file and not map object,and I dont want to use external library such as numpy

Thanks

Was it helpful?

Solution

You can use list comprehension as such:

myfile.txt:

1 2 3
4 5 6
7 8 9


>>> matrix = open('myfile.txt').read()
>>> matrix = [item.split() for item in matrix.split('\n')[:-1]]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>> 

You can also create a function for this:

>>> def matrix(file):
...     contents = open(file).read()
...     return [item.split() for item in contents.split('\n')[:-1]]
... 
>>> matrix('myfile.txt')
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>> 

OTHER TIPS

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

rows=3
cols=3
with open('in.txt') as f:
   data = []
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top