寫入檔案物件時返回值

在 Python 2 中,直接寫入檔案控制代碼返回 None

Python 2.x >= 2.3

hi = sys.stdout.write('hello world\n')
# Out: hello world
type(hi)
# Out: <type 'NoneType'>

在 Python 3 中,寫入控制代碼將返回寫入文字時寫入的字元數,以及寫入位元組時寫入的位元組數:

Python 3.x >= 3.0

import sys

char_count = sys.stdout.write('hello world 🐍\n')
# Out: hello world 🐍
char_count
# Out: 14

byte_count = sys.stdout.buffer.write(b'hello world \xf0\x9f\x90\x8d\n')
# Out: hello world 🐍
byte_count
# Out: 17