GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing python.github.io — 7. Input and output — Python 3.15.2 說明文件 7. Input and output¶有數種方式可以顯示程式的輸出;資料可以以人類易讀的形式印出,或是寫入檔案以供未來所使用。這章節會討論幾種不同的方式。 7.1. Fancier output formatting¶目前為止我們已經學過兩種寫值的方式:運算式陳述 (expression statements) 與 通常你會想要對輸出格式有更多地控制,而不是僅列印出以空格隔開的值。以下是幾種格式化輸出的方式。
如果你不需要華麗的輸出,只想快速顯示變數以進行除錯,可以用
一些範例: >>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" >>> str(1/7) '0.14285714285714285' >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>> print(s) The value of x is 32.5, and y is 40000... >>> # 字串的 repr() 會加上字串引號和反斜線: >>> hello = 'hello, world\n' >>> hellos = repr(hello) >>> print(hellos) 'hello, world\n' >>> # repr() 的引數可以是任何 Python 物件: >>> repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))"
7.1.1. Formatted string literals¶格式化的字串文本(簡稱為 f-字串),透過在字串加入前綴 格式說明符 (format specifier) 是選擇性的,寫在運算式後面,可以更好地控制值的格式化方式。以下範例將 pi 捨入到小數點後三位: >>> import math >>> print(f'The value of pi is approximately {math.pi:.3f}.') The value of pi is approximately 3.142. 在 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print(f'{name:10} ==> {phone:10d}') ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678 還有一些修飾符號可以在格式化前先將值轉換過。 >>> animals = 'eels' >>> print(f'My hovercraft is full of {animals}.') My hovercraft is full of eels. >>> print(f'My hovercraft is full of {animals!r}.') My hovercraft is full of 'eels'.
>>> bugs = 'roaches' >>> count = 13 >>> area = 'living room' >>> print(f'Debugging {bugs=} {count=} {area=}') Debugging bugs='roaches' count=13 area='living room' 更多關於 7.1.2. The string format() method¶
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!" 大括號及其內的字元(稱為格式欄位)會被取代為傳遞給 >>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs >>> print('{1} and {0}'.format('spam', 'eggs')) eggs and spam 如果在 >>> print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) This spam is absolutely horrible. 位置引數和關鍵字引數可以任意組合: >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', ... other='Georg')) The story of Bill, Manfred, and Georg. 如果你有一個不想分割的長格式化字串,比較好的方式是按名稱而不是按位置來引用變數。這項操作可以透過傳遞字典 (dict),並用方括號 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' ... 'Dcab: {0[Dcab]:d}'.format(table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 用 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 與內建函式 >>> table = {k: str(v) for k, v in vars().items()} >>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()]) >>> print(message.format(**table)) __name__: __main__; __doc__: None; __package__: None; __loader__: ... 例如,下面的程式碼產生一組排列整齊的欄,列出整數及其平方與立方: >>> for x in range(1, 11): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 關於使用 7.1.3. Manual string formatting¶下面是以手動格式化完成的同一個平方及立方的表: >>> for x in range(1, 11): ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') ... # 注意前一列使用的 'end' ... print(repr(x*x*x).rjust(4)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 (請注意,使用 字串物件的 另一種 method 是 >>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> '3.14159265359'.zfill(5) '3.14159265359' 7.1.4. 格式化字串的舊方法¶% 運算子(modulo,模數)也可用於字串格式化。在 >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. 更多資訊請見 printf-style String Formatting小節。 7.2. Reading and writing files¶
>>> f = open('workfile', 'w') 第一個引數是一個包含檔案名稱的字串。第二個引數是另一個字串,包含了描述檔案使用方式的幾個字元。mode 為 Normally, files are opened in text mode, that means, you read and write
strings from and to the file, which are encoded in a specific encoding.
If encoding is not specified, the default is UTF-8 (see 在文字模式 (text mode) 下,讀取時會預設把平台特定的行尾符號(Unix 上為 在處理檔案物件時,使用 >>> with open('workfile') as f: ... read_data = f.read() >>> # We can check that the file has been automatically closed. >>> f.closed True 如果你沒有使用 警告 呼叫 不論是透過 >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file. 7.2.1. Methods of file objects¶本節其餘的範例皆假設一個名為 要讀取檔案的內容,可呼叫 >>> f.read() 'This is the entire file.\n' >>> f.read() ''
>>> f.readline() 'This is the first line of the file.\n' >>> f.readline() 'Second line of the file\n' >>> f.readline() '' 想從檔案中讀取多行時,可以對檔案物件進行迴圈。這種方法能有效地使用記憶體、快速,且程式碼簡潔: >>> for line in f: ... print(line, end='') ... This is the first line of the file. Second line of the file 如果你想把一個檔案的所有行讀進一個 list 裡,可以用
>>> f.write('This is a test\n') 15 寫入其他類型的物件之前,要先把它們轉換為字串(文字模式)或位元組串物件(二進制模式): >>> value = ('the answer', 42) >>> s = str(value) # 將元組轉換成字串 >>> f.write(s) 18
使用 >>> f = open('workfile', 'rb+') >>> f.write(b'0123456789abcdef') 16 >>> f.seek(5) # 跳到檔案中的第六個位元組 5 >>> f.read(1) b'5' >>> f.seek(-3, 2) # 跳到結尾前的第三個位元組 13 >>> f.read(1) b'd' 在文字檔案(開啟時模式字串未加入 檔案物件還有一些附加的 method,像是較不常使用的 7.2.2. 使用
|
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |