Formatted I/O 格式化讀寫

python 格式碼 format code

the format code parameter: %[flag]width[.precision]types (field in [] is optional)

  • flags:
    • - = left justify,
    • + = Forces to precede result with + or -,
    • 0 = Left pad the number with zeros instead of space (set by "width").
  • width: Minimum number of characters to be printed.
  • precision:
    • For d type, the minimum number of digits.
    • For e, and f types, the number of digits to print after the decimal point.
    • For g, the maximum number of significant digits.
    • For s, the maximum number of characters.
  • types:
    • d: signed decimal integer (e.g., 100)
    • e: scientific notation with e (e.g. 1.e+2)
    • f: decimal floating point (e.g., 100.00)
    • g: use the shorter of e or f
    • s: string

for complete list of format code option, see reference: https://docs.python.org/3/library/string.html#format-specification-mini-language

In [1]:
# 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.
Out[1]:
34

np.savetxt/np.loadtxt Numpy 檔案格式化輸出讀入

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

example

一樣用一個元素為0~99的10x10二維陣列的輸出、讀取來舉例(請參考Numpy_FileIO單元)

In [2]:
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]]
In [ ]: