Zigii Wong
Zigii Wong

Reputation: 7826

Import matrix from .txt file with format

Very new to python. Let say I have a txt file which contains a matrix.

matrix.txt

A A A B B C
D D C D A E
A D S A W A

Now I want to import this matrix to my python program so that I can deal with the data. Now the question is how should I do to append each line of matrix?

What I tried:

file_object = open('matrix.txt', 'r')
try:
   line = file_object.readline()
   while line:
       print line
       line = file_object.readline()
       line = line.strip()
       string = []
       string.append(line)
       print string
finally:
   file_object.close()
print string[0][1]

Edit: Special situation:

A A A B B C           A A A B B C
  D C D A E   --->    0 D C D A E
  D   A W A           0 D 0 A W A

So if some elements are nil, how could I replace them with 0?

Upvotes: 1

Views: 442

Answers (3)

AllBlackt
AllBlackt

Reputation: 720

A bit exhaustive code with explanations:

#define a separator which divides your elements
sep = ' '
matrix = []
with open('matrix.txt', 'r') as f:
    for line in f:
        # generate an array with the elements which are on the line
        line_array = line.split(sep)

        #append it to the matrix
        matrix.append(line_array)

print matrix

In order to better understand the 'with' statement, read this, it helped me.

Edit: In order to match double-separators as a nil (None) object, replace the line_array association with:

line_array = [e or 0 for e in line.split(sep)]

Example dataset (notice double space between B and C):

A A A B  C
D D C D A E
A D S A W A

Edit 2: For platform independent line endings, use:

line_array = [e or 0 for e in line.splitlines()[0].split(sep)]

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16721

with open('matrix.txt') as data:
    matrix = [i.split() for i in data]

Upvotes: 1

kvorobiev
kvorobiev

Reputation: 5070

You can use

matrix = []
for lines in open('matrix.txt', 'r'):
    matrix.append(lines.split())

Upvotes: 0

Related Questions