Q:

Python from matrix to simple text file

I would like to ask you how to change file looks like this:
 123 111 1
 146 204 2
 178 398 1
 ...
 ...

First column is x, second is y and the third mean the number in each square.
My matrix is 400x400 dimension. I would like to change it to the simple file 
M file doesn't posses every square (for example 0 0 doesn't exist which mean that in output file i would like to have 0 in first row in first place.
My output file should look like this 
 0 0 1 0 0 0 1 0 7 9 3 0 2 0 ...
 8 0 0 1 0 0 0 0 0 0 0 0 0 0 ...
 7 8 9 0 7 5 0 0 3 2 4 5 5 7 ...
 ...
 ...

How can I change my file?
From first file i would like to reah second file. Like text file with 400lines each 400 characters splited by " " (blankspace). 

A:

Just initialize your matrix as as a list of list of zeros, and then iterate the lines in the file and set the values in the matrix accordingly. Cells that are not in the file will remain unchanged.
matrix = [[0 for i in range(400)] for k in range(400)]
with open("filename") as data:
    for row in data:
        (x, y, n) = map(int, row.split())
        matrix[x][y] = n

Finally, write that matrix to another file:
with open("outfile", "w") as outfile:
    for row in matrix:
        outfile.write(" ".join(map(str, row)) + "\n")

You could also use numpy:
matrix = numpy.zeros((4,4), dtype=numpy.int8)

