# Python 輸入和輸出
在前面幾個章節中,我們其實已經接觸了 Python 的輸入輸出的功能。本章節我們將具體介紹 Python 的輸入輸出。
## 輸出格式美化
Python兩種輸出值的方式: 表達式語句 和 print() 函數。(第三種方式是使用文件對象的 write() 方法; 標準輸出文件可以用 sys.stdout 引用。)
如果你希望輸出的形式更加多樣,可以使用 str.format() 函數來格式化輸出值。
如果你希望將輸出的值轉成字符串,可以使用 repr() 或 str() 函數來實現。
str() 函數返回一個用戶易讀的表達形式。
repr() 產生一個解釋器易讀的表達形式。
### 例如
```
>>> 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...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
```
這里有兩種方式輸出一個平方與立方的表:
```
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of 'end' on previous line 注意前一行 '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
>>> 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
```
**注意:**在第一個例子中, 每列間的空格由 print() 添加。
這個例子展示了字符串對象的 rjust() 方法, 它可以將字符串靠右, 并在左邊填充空格。
還有類似的方法, 如 ljust() 和 center()。 這些方法并不會寫任何東西, 它們僅僅返回新的字符串。
另一個方法 zfill(), 它會在數字的左邊填充 0,如下所示:
```
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
```
str.format() 的基本使用如下:
```
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
```
括號及其里面的字符 (稱作格式化字段) 將會被 format() 中的參數替換。
在括號中的數字用于指向傳入對象在 format() 中的位置,如下所示:
```
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
```
如果在 format() 中使用了關鍵字參數, 那么它們的值會指向使用該名字的參數。
```
>>> 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.
```
'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某個值之前對其進行轉化:
```
>>> import math
>>> print('The value of PI is approximately {}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately {!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.
```
可選項 ':' 和格式標識符可以跟著字段名。 這就允許對值進行更好的格式化。 下面的例子將 Pi 保留到小數點后三位:
```
>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.
```
在 ':' 后傳入一個整數, 可以保證該域至少有這么多的寬度。 用于美化表格時很有用。
```
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
```
如果你有一個很長的格式化字符串, 而你不想將它們分開, 那么在格式化時通過變量名而非位置會是很好的事情。
最簡單的就是傳入一個字典, 然后使用方括號 '[]' 來訪問鍵值 :
```
>>> 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 變量前使用 '**' 來實現相同的功能:
```
>>> 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
```
## 舊式字符串格式化
% 操作符也可以實現字符串格式化。 它將左邊的參數作為類似 sprintf() 式的格式化字符串, 而將右邊的代入, 然后返回格式化后的字符串. 例如:
```
>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.
```
因為 str.format() 比較新的函數, 大多數的 Python 代碼仍然使用 % 操作符。但是因為這種舊式的格式化最終會從該語言中移除, 應該更多的使用 str.format().
## 讀和寫文件
open() 將會返回一個 file 對象,基本語法格式如下:
```
open(filename, mode)
```
實例:
```
>>> f = open('/tmp/workfile', 'w')
```
* 第一個參數為要打開的文件名。
* 第二個參數描述文件如何使用的字符。 mode 可以是 'r' 如果文件只讀, 'w' 只用于寫 (如果存在同名文件則將被刪除), 和 'a' 用于追加文件內容; 所寫的任何數據都會被自動增加到末尾. 'r+' 同時用于讀寫。 mode 參數是可選的; 'r' 將是默認值。
## 文件對象的方法
本節中剩下的例子假設已經創建了一個稱為 f 的文件對象。
### f.read()
為了讀取一個文件的內容,調用 f.read(size), 這將讀取一定數目的數據, 然后作為字符串或字節對象返回。
size 是一個可選的數字類型的參數。 當 size 被忽略了或者為負, 那么該文件的所有內容都將被讀取并且返回。
```
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
```
### f.readline()
f.readline() 會從文件中讀取單獨的一行。換行符為 '\n'。f.readline() 如果返回一個空字符串, 說明已經已經讀取到最后一行。
```
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
```
### f.readlines()
f.readlines() 將返回該文件中包含的所有行。
如果設置可選參數 sizehint, 則讀取指定長度的字節, 并且將這些字節按行分割。
```
>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
```
另一種方式是迭代一個文件對象然后讀取每行:
```
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
```
這個方法很簡單, 但是并沒有提供一個很好的控制。 因為兩者的處理機制不同, 最好不要混用。
### f.write()
f.write(string) 將 string 寫入到文件中, 然后返回寫入的字符數。
```
>>> f.write('This is a test\n')
15
```
如果要寫入一些不是字符串的東西, 那么將需要先進行轉換:
```
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
18
```
### f.tell()
f.tell() 返回文件對象當前所處的位置, 它是從文件開頭開始算起的字節數。
### f.seek()
如果要改變文件當前的位置, 可以使用 f.seek(offset, from_what)函數, from_what 表示開始讀取的位置,offset表示從from_what再移動一定量的距離,比如f.seek(10, 3)表示定位到第三個字符并再后移10個字符。
from_what值為0時表示文件的開始,它也可以省略,缺省是0即文件開頭。下面給出一個完整的例子:
```
>>> f = open('/tmp/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'
```
### f.close()
在文本文件中 (那些打開文件的模式下沒有 b 的), 只會相對于文件起始位置進行定位。
當你處理完一個文件后, 調用 f.close() 來關閉文件并釋放系統的資源,如果嘗試再調用該文件,則會拋出異常。
```
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
<pre>
<p>
當處理一個文件對象時, 使用 with 關鍵字是非常好的方式。在結束后, 它會幫你正確的關閉文件。 而且寫起來也比 try - finally 語句塊要簡短:</p>
<pre>
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
```
文件對象還有其他方法, 如 isatty() 和 trucate(), 但這些通常比較少用。
## pickle 模塊
python的pickle模塊實現了基本的數據序列和反序列化。
通過pickle模塊的序列化操作我們能夠將程序中運行的對象信息保存到文件中去,永久存儲。
通過pickle模塊的反序列化操作,我們能夠從文件中創建上一次程序保存的對象。
基本接口:
```
pickle.dump(obj, file, [,protocol])
```
有了 pickle 這個對象, 就能對 file 以讀取的形式打開:
```
x = pickle.load(file)
```
**注解:**從 file 中讀取一個字符串,并將它重構為原來的python對象。
**file:** 類文件對象,有read()和readline()接口。
實例1:
```
#使用pickle模塊將數據對象保存到文件
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
```
實例2:
```
#使用pickle模塊從文件中重構python對象
import pprint, pickle
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
```
- Python 基礎教程
- Python 簡介
- Python 環境搭建
- Python 基礎語法
- Python 變量類型
- Python 運算符
- Python 條件語句
- Python 循環語句
- Python While循環語句
- Python for 循環語句
- Python 循環嵌套
- Python break 語句
- Python continue 語句
- Python pass 語句
- Python 數字
- Python 字符串
- Python 列表(Lists)
- Python 元組
- Python 字典(Dictionary)
- Python 日期和時間
- Python 函數
- Python 模塊
- Python 文件I/O
- Python 異常處理
- Python 高級教程
- Python 面向對象
- Python 正則表達式
- Python CGI編程
- Python 使用SMTP發送郵件
- Python 多線程
- Python 2.x與3??.x版本區別
- Python IDE
- Python JSON
- Python3 教程
- Python3 基礎語法
- Python3 基本數據類型
- Python3 解釋器
- Python3 注釋
- Python3 數字運算
- Python3 字符串
- Python3 列表
- Python3 編程第一步
- Python3 條件控制
- Python3 循環
- Python3 函數
- Python3 數據結構
- Python3 模塊
- Python3 輸入和輸出
- Python3 錯誤和異常
- Python3 類
- Python3 標準庫概覽
- 免責聲明