打印進度條的方法用兩種:
一、sys.stdout.write方式
這個方法中必須使用這句話每次來清理緩存。
sys.stdout.flush()
import sys
import time
i = 0
for i in range(20):
time.sleep(1)
sys.stdout.write("\r# Process: %0.1f %%" % (float(i + 1) / float(20) * 100))
sys.stdout.flush()
二、print方式
其中用print(’’,end=’’)來實現sys.stdout.write()
import time
i = 0
for i in range(20):
time.sleep(1)
print("\r# Process: %0.1f %%" % (float(i + 1) / float(20) * 100),end="")
結果如圖1所示:
圖1
三、\r等轉義字符操作
轉義字符 | 描述 |
---|---|
\ | 反斜槓符號 |
\r | 回車 |
\t | 橫向製表符 |
\n | 換行 |
\’ | 單引號 |
\” | 雙引號 |
\oyy | 八進制數yy代表的字符,例如:\o12代表換行 |
\xyy | 十進制數yy代表的字符,例如:\x0a代表換行 |
\f | 換頁 |
\b | 退格(Backspace) |