0

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

2 Answers 2

2

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

2 Comments

Thanks for helping; I tried your list comprehension,however,I created a file with the matrix 1 2 3,under those,4 5 6 and under 4 5 6, 7 8 9; It doest work but only write 1 2 3 and 4 5 6 in the matrix, 7 8 9 is not showing/saved?
I removed [:-1] from your code and now it works as I wish; what was [:-1] for? Thanks
0

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)

Comments

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.