In [1]:
%pylab --no-import-all inline
In [2]:
dimension = 10
matrix = np.random.random(dimension * dimension).reshape(dimension, dimension)
print(matrix)
In [3]:
def print_matrix(matrix, ncol=4):
dimension = matrix.shape[0]
j = 0
out = ""
while j < dimension:
jmax = min(dimension, j + ncol)
out += 5 * " " + " ".join(["%12d" % jj for jj in range(j, jmax)]) + "\n"
for i in range(dimension):
out += "%5d" % i
out += " ".join(["%12.6f" % matrix[i, jj] for jj in range(j, jmax)]) + "\n"
j += ncol
return out
out = print_matrix(matrix)
print(out)
In [4]:
with open("matrix.dat", "w") as f:
f.write("A title and blank lines\n\n\n")
f.write("$matrix\n")
f.write("%d\n" % dimension)
f.write("\n")
f.write(out)
In [5]:
cat matrix.dat
In [6]:
with open("matrix.dat", "r") as f:
for i in range(7):
line = f.readline()
print(line.strip())
In [7]:
with open("matrix.dat", "r") as f:
[f.readline() for i in range(3)]
line = f.readline()
print(line)
In [8]:
def read_matrix(filename):
with open(filename, "r") as f:
# read dimension
dimension = None
while not dimension:
line = f.readline()
if "$matrix" in line:
dimension = int(f.readline())
print("dimension :", dimension)
# allocate matrix
matrix = np.zeros((dimension, dimension))
# read the blanck line
f.readline()
# read the matrix
while line != "":
line = f.readline()
jindex = [int(jj) for jj in line.split()]
for i in range(dimension):
line = f.readline()
data = [float(val) for val in line.split()[1:]]
for k, val in enumerate(data):
matrix[i, jindex[k]] = val
return matrix
rmatrix = read_matrix("matrix.dat")
out = print_matrix(rmatrix)
print(out)
In [9]:
with open("matrix.dat", "r") as f:
line = next(f)
print("line 1", line.strip())
[next(f) for i in range(5)]
line = next(f)
print("line 2", line.strip())
print(10*"------")
i = 0
for line in f:
i += 1
print(line.strip())
if i == 5:
break
print(10*"------")
i = 0
while i < 6:
i += 1
line = f.readline()
print(line.strip())