the format code parameter: %[flag]width[.precision]types (field in [] is optional)
for complete list of format code option, see reference: https://docs.python.org/3/library/string.html#format-specification-mini-language
# Open a file
a=3.1
b=4.2
fo = open("foo_format.txt", "w") # open for writing only
fo.write('The results of %4.2f + %4.2f = %5.3f' %(a,b,a+b)) # output string to the file.
34
numpy.savetxt(fname, var, fmt='...', delimiter='...', newline='\n', header='...', footer='...', comments='...')
fmt : 自訂輸出格式
delimiter : 分隔符號,預設為空白(whitespace)
newline : 隔開新行的符號(預設為\n)
ndarray=numpy.loadtxt(fname, dtype='...', delimiter='...', comments='...', skiprows=..., usecols=...,unpack=...)
dtype : 資料型態(float, int, str),預設為float。
comments : 註解符號,預設為'#'。
delimiter : 分隔符號,預設為空白(whitespace)
參考連結 : https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
參考連結 : https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html
一樣用一個元素為0~99的10x10二維陣列的輸出、讀取來舉例(請參考Numpy_FileIO單元)
import numpy as np
A = np.arange(100).reshape(10,10) #convert the 100x1 array to a 10x10 array
np.savetxt('Aout_format.txt',A, fmt='%+5.3d',delimiter=',')
B=np.loadtxt('Aout_format.txt',dtype='int',delimiter=',')
print(B)
[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]]