1. Introducción
Cuando las necesidades del proceso de cálculo para ser registrados, un enfoque alternativo es procesar el archivo txt cálculo de la salida, si se trata de la salida de un número o un vector o una matriz, se necesita nada más se
- subtítulo
- datos
- Formato de salida
Al escribir file.write, sólo se puede escribir una cadena, a fin de utilizar el paquete ya hecho es mejor, auto OutTxt.py
2. Programa
# coding=UTF-8
# 保存为OutTxt.py
def Real(FilePath,Matrix,Fmt='w',**Option):
if 'width' in Option:
N = Option['width']
else:
N = 8
if 'string' in Option:
string = Option['string']
else:
string = '输出的矩阵:\n'
with open(FilePath,Fmt) as file:
NumR,NumC = Matrix.shape
file.write(string)
for i in range(NumR):
for j in range(NumC):
file.write(str(Matrix[i,j]).ljust(N+1)[0:N-1])
file.write(' ')
file.write('\n')
def Complex(FilePath,Matrix,Fmt='w',**Option):
if 'width' in Option:
N = Option['width']
else:
N = 8
if 'string' in Option:
string = Option['string']
else:
string = '输出的矩阵:\n'
RealM = Matrix.real
ImagM = Matrix.imag
# print(FilePath)
with open(FilePath,Fmt) as file:
NumR,NumC = Matrix.shape
file.write(string)
for i in range(NumR):
for j in range(NumC):
file.write(str(RealM[i,j]).ljust(N+1)[0:N-1])
file.write('+')
file.write('j'+str(ImagM[i,j]).ljust(N+1)[0:N-1])
file.write(' ')
file.write('\n')
3. Prueba
#------将矩阵写入txt-------#
import OutTxt
import numpy as np
Z = np.random.rand(5,5)+np.random.rand(5,5)*1j
OutTxt.Complex('Complex.txt',Z,'w',string='My Matrix:\n',width=10) # 实数矩阵
OutTxt.Real('Real.txt',Z.real,'w',string='My Matrix:\n',width=9) # 复数矩阵
4. resultados
(Signo también ser discutido)
# complex.txt如下:
My Matrix:
0.5278015+j0.6348834 0.9629084+j0.1729091 0.9709622+j0.5446667 0.6142698+j0.8098638 0.7727490+j0.3458784
0.8532371+j0.0387547 0.3347495+j0.2680946 0.7926111+j0.9664751 0.3348781+j0.1489805 0.2930090+j0.0333537
0.3044924+j0.6159243 0.4662545+j0.4494182 0.2083607+j0.1815810 0.1977293+j0.7392929 0.3890427+j0.5362721
0.7181048+j0.1502132 0.3751771+j0.8522980 0.4731115+j0.2077804 0.4185118+j0.7511989 0.6989816+j0.4166925
0.1645633+j0.2876576 0.9031527+j0.2020653 0.3816732+j0.4030742 0.0616005+j0.3891945 0.2463344+j0.7085873
# Real.txt如下:
My Matrix:
0.527801 0.962908 0.970962 0.614269 0.772749
0.853237 0.334749 0.792611 0.334878 0.293009
0.304492 0.466254 0.208360 0.197729 0.389042
0.718104 0.375177 0.473111 0.418511 0.698981
0.164563 0.903152 0.381673 0.061600 0.246334