Python学习笔记(五)-实数/复数矩阵输出到txt文件(有格式选择)
2018-01-21 23:49
881 查看
1. 前言
当需要对计算过程进行记录时,一个可选的方案是将计算过程输出到txt文件中,无论是输出一个数,还是一个向量,还是一个矩阵,无非需要的是文字说明
数据
输出格式
用file.write写入时,只能写入一个字符串,所以用现成的包比较好,自编OutTxt.py
2. 程序
# 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. 测试
#------将矩阵写入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. 结果
(也可对正负号进行讨论)
# 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
版权声明:本文为博主原创文章,未经博主允许不得转载。
相关文章推荐
- NetworkX学习笔记-3-Python中输出Gephi文件格式的方法
- NetworkX学习笔记-3-Python中输出Gephi文件格式的方法
- ArcEngine 9.3 学习笔记(十一):地图输出(Printer类,PageLayoutControl控件打印出图,栅格格式文件输出,矢量格式文件输出)
- 关于Python中输出文件选择格式问题
- Python学习笔记-Txt文件转Excel文件
- 用Python将gml文件中边的信息输出为csv(或者txt)格式
- python学习笔记(1)--遍历txt文件,正则匹配替换文字
- 简明Python教程学习笔记_7_输入输出和文件操作
- python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码
- Python输入输出格式相关学习笔记
- python筛选特定文件的信息按照格式输出到txt
- Excel开发学习笔记:文件选择控件、查找匹配项、单元格格式及数据有效性
- java学习笔记 读取pdf文件并写成txt文件输出
- Spring MVC 学习笔记 json格式的输入和输出
- Python 学习笔记【文件对象】
- 2012/2/11 《C++ Primer Plus》第十七章:输入、输出和文件 学习笔记
- Python学习笔记整理(七)Python中的元组和文件及其他
- PE文件格式学习笔记(一) 转自http://blog.csdn.net/hbyufan/
- Spring MVC 学习笔记 PDF/Excel格式输出
- python学习笔记——文件